[C/C++标准库]_[初级]_[构造文件路径(stringByAppendingPathComponent)]
来源:互联网 发布:wayv 源码 编辑:程序博客网 时间:2024/06/17 16:47
场景:
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.txtC:\info/info.txt
0 0
- [C/C++标准库]_[初级]_[构造文件路径(stringByAppendingPathComponent)]
- [C/C++标准库]_[初级]_[读写中文路径的文件--写入unicode字符串]
- [C/C++标准库]_[初级]_[使用时间库]
- [C/C++标准库]_[初级]_[signal信号浅析]
- [C/C++标准库]_[初级]_[集合操作]
- [C/C++标准库]_[初级]_[使用string stream]
- [C/C++标准库]_[初级]_[分割字符串Split]
- [C/C++标准库]_[初级]_[unary_function 和 binary_function]
- [C/C++标准库]_[初级]_[unary_function 和 binary_function]
- [C/C++标准库]_[初级]_[C++ iostream read getline 读取文件慢的原因]
- [C/C++标准库]_[初级]_[获取文件的所在目录跨平台实现]
- [C/C++标准库]_[初级]_[标准库里提供的排序算法]
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]
- [C/C++标准库]_[初级]_[对C链表排序]
- [C/C++标准库]_[初级]_[不使用正则替换和删除字符串]
- [C/C++标准库]_[初级]_[自定义std::map的key]
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- [C/C++标准库]_[初级]_[std::vector的删除元素]
- Unity3D经典题型
- 角色控制器
- cocos2dx3.x利用sokcet创建客户端和服务端 (三)
- 学习machine learning foundation 感想
- Qt5生成程序自定义显示图标
- [C/C++标准库]_[初级]_[构造文件路径(stringByAppendingPathComponent)]
- UITextField属性及方法大总结
- 设计模式 门面模式
- POJ1258 - Agri-Net
- java.lang.reflect.InvocationTargetException异常
- Android学习笔记之获取手机屏幕大小
- 写给java初学者
- 批处理删除临时文件,垃圾文件更新存档
- Linux程序设计 第1章入门 第2章shell程序设计