您的位置:首页 > 移动开发

[C/C++标准库]_[初级]_[构造文件路径(stringByAppendingPathComponent)]

2014-12-19 23:04 375 查看
场景:

1. 很多情况下需要通过文件夹和文件名拼接文件路径字符串,每次都需要判断是否需要添加路径分隔符seperator很麻烦,所以可以写一个通用函数.

2. 大多数情况下都是windows使用wstring,mac使用string,所以用模版实现最通用.

3. Cocoa里的NSString有这个方法是相同的作用,stringByAppendingPathComponent.

函数:

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



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: