场景:
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.txt C:\info/info.txt
时间: 2024-10-13 20:49:13