【发布时间】:2012-04-28 15:23:17
【问题描述】:
我有
const char *pathname = "..\somepath\somemorepath\somefile.ext";
如何转换成
"..\somepath\somemorepath"
?
【问题讨论】:
-
Boost 有一个不错的
filesystem::path类...
标签: c++ string filesystems
我有
const char *pathname = "..\somepath\somemorepath\somefile.ext";
如何转换成
"..\somepath\somemorepath"
?
【问题讨论】:
filesystem::path 类...
标签: c++ string filesystems
最简单的方法是使用std::string的成员函数find_last_of
string s1("../somepath/somemorepath/somefile.ext");
string s2("..\\somepath\\somemorepath\\somefile.ext");
cout << s1.substr(0, s1.find_last_of("\\/")) << endl;
cout << s2.substr(0, s2.find_last_of("\\/")) << endl;
此解决方案适用于正斜杠和反斜杠。
【讨论】:
在 Windows 上使用 _splitpath(),在 Linux 上使用 dirname()
【讨论】:
在 Windows 8 上,使用PathCchRemoveFileSpec,可以在Pathcch.h 中找到
PathCchRemoveFileSpec 将删除路径中的最后一个元素,因此如果您将目录路径传递给它,最后一个文件夹将被删除。
如果您想避免这种情况,并且不确定文件路径是否为目录,请使用PathIsDirectory
PathCchRemoveFileSpec 在包含正斜杠的路径上的行为不符合预期。
【讨论】:
使用strrchr() 查找最后一个反斜杠并删除字符串。
char *pos = strrchr(pathname, '\\');
if (pos != NULL) {
*pos = '\0'; //this will put the null terminator here. you can also copy to another string if you want
}
【讨论】:
/) 怎么办?
PathRemoveFileSpec(...) 你不需要 Windows 8。 您将需要包括 Shlwapi.h 和 Shlwapi.lib 但它们是winapi,所以你不需要任何特殊的SDK
【讨论】: