29

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";

如何将其转换为

"..\somepath\somemorepath"

?

4

5 回答 5

59

最简单的方法是使用find_last_of成员函数std::string

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;

此解决方案适用于正斜杠和反斜杠。

于 2012-04-28T15:29:28.080 回答
9

在 Windows 上使用_splitpath()和在 Linux 上使用dirname()

于 2012-04-28T15:26:44.447 回答
6

On Windows 8, use PathCchRemoveFileSpec which can be found in Pathcch.h

PathCchRemoveFileSpec will remove the last element in a path, so if you pass it a directory path, the last folder will be stripped.
If you would like to avoid this, and you are unsure if a file path is a directory, use PathIsDirectory

PathCchRemoveFileSpec does not behave as expected on paths containing forwards slashes.

于 2013-09-11T00:34:12.757 回答
3

用于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
}
于 2012-04-28T15:26:34.133 回答
0

PathRemoveFileSpec(...) 你不需要 Windows 8。你需要包括 Shlwapi.h 和 Shlwapi.lib 但它们是 winapi 所以你不需要任何特殊的 SDK

于 2019-10-10T22:43:11.480 回答