標籤:路徑 斜杠 反斜線 轉義
#include <boost\shared_ptr.hpp>盡量不要使用\,而是使用/,這樣子方面移植代碼到Linux 環境下
代碼如下:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char utfBuffer[256] = {0};
ifstream utffile("E:/doc/Android/Makefile");//OK
//ifstream utffile("E:\doc\Android\Makefile");//ERROR
//ifstream utffile("E:\\doc\\Android\\Makefile");//OK
utffile.getline(utfBuffer, 100);
size_t inLen = strlen(utfBuffer);
return 0;
}
總結:
第一種方案採用和Unix系統一樣的斜杠,方便在以後的開發中移植到Linux平台,畢竟標頭檔include中斜杠的修改比較麻煩。
第三種方法採用雙反斜線,告訴編譯器前面的反斜線不是用來屏蔽轉義的,而是實實在在存在的。
第二種錯誤方案,詳細分析:
拆分字串:
char utfBuffer[256] = {0};
char szPathName[256] ={"E:\doc\Android\Makefile"};
ifstream utffile(szPathName);
utffile.getline(utfBuffer, 100);
size_t inLen = strlen(utfBuffer);
return 0;
通過單步調試szPathName的實際內容變成:"E:docAndroidMakefile" 編譯器認為\是用來禁止轉義用的,而沒有想到使用者實際上是作為反斜線,因此將其清除,導致讀取檔案路徑失敗
經驗 windows目錄\在實際開發中使用/代替