標籤:c++ 檔案路徑 合并 串連 stringbyappendingpat
情境:
1. 很多情況下需要通過檔案夾和檔案名稱拼接檔案路徑字串,每次都需要判斷是否需要添加路徑分隔字元seperator很麻煩,所以可以寫一個通用函數.
2. 大多數情況下都是windows使用wstring,mac使用string,所以用模版實現最通用.
函數:
template<class T>T AppendPathComponent(const T& source,const T& component){int length = source.length();int last = (length)?(length-1):0;if(source[last] == 0x5C || source[last] == 0x2F){return source+component;}else{T path(source);path.resize(length+1);path[length] = 0x2F;path.append(component);return path;}}inline char* Unicode2Ansi(const wchar_t* unicode) { int len; len = WideCharToMultiByte(CP_ACP, 0, unicode, -1, NULL, 0, NULL, NULL); char *szUtf8 = (char*)malloc(len + 1); memset(szUtf8, 0, len + 1); WideCharToMultiByte(CP_ACP, 0,unicode, -1, szUtf8, len, NULL,NULL); return szUtf8; }
調用:
std::wstring wpath(L"C:\\info/中文");std::wstring wpath_1 = AppendPathComponent(wpath,std::wstring(L"info.txt"));cout << Unicode2Ansi(wpath_1.c_str()) << endl;std::string path("C:\\info");std::string path_1 = AppendPathComponent(path,std::string("info.txt"));cout << path_1.c_str()<< endl;
輸出:
C:\info/中文/info.txtC:\info/info.txt
[C/C++標準庫]_[初級]_[構造檔案路徑(stringByAppendingPathComponent)]