自己做直播网站优化大师班级
我们可能会经常遇到文件所在文件夹路径的问题,虽然各大平台也有提供方便快捷的API来实现,但是如果脱离平台本身,或者想实现跨平台的话,可以考虑用纯C++的代码来实现这一需求
示例代码
#include <string>
#include <iostream>
using std::wstring;//
wstring GetParentFolderPath(wstring path)
{size_t colon = path.find(L':');std::wstring vol = path.substr(0, colon + 1);if (colon != path.npos) {path = path.substr(colon + 1);}size_t last = path.rfind(L'\\');if (last == path.npos) {path.clear();}else if (last == 0) {path.resize(1);}else {// 去除末尾的斜杠 if (!path.empty() && (last == path.size() - 1)){path.resize(path.size() - 1);last = path.rfind(L'\\');}if (last == path.npos) {path.clear();}else {path.resize(last + 1);}}if (!vol.empty() && path.empty()) {return vol + L"\\";}else {return vol + path;}
}int main()
{std::wstring wsz0 = GetParentFolderPath(L"C:\\Program Files (x86)\\QQ\\log");std::wstring wsz1 = GetParentFolderPath(L"C:\\Program Files (x86)\\QQ");std::wstring wsz2 = GetParentFolderPath(L"C:\\Program Files (x86)");std::wstring wsz3 = GetParentFolderPath(L"C:");std::wcout << "wsz0: " << wsz0.c_str() << std::endl;std::wcout << "wsz1: " << wsz1.c_str() << std::endl;std::wcout << "wsz2: " << wsz2.c_str() << std::endl;std::wcout << "wsz3: " << wsz3.c_str() << std::endl;system("pause");return 0;
}
输出结果
wsz0: C:\Program Files (x86)\QQ
wsz1: C:\Program Files (x86)
wsz2: C:
wsz3: C:\