C++如何从路径字符串中删除文件名

31

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";
如何将其转换为
"..\somepath\somemorepath"

?


Boost有一个很好的filesystem::path类... - Cameron
6个回答

62

最简单的方法是使用std::stringfind_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;

这个解决方案适用于前斜杠和后斜杠。


8
只要用户不在文件名中使用任何合法的斜杠,它就能正常工作。 - Potatoswatter
对我没用,但这个可以:https://dev59.com/mWoy5IYBdhLWcg3wfOF4 - brad

11

7
在Windows 8上,使用PathCchRemoveFileSpec,该函数可以在Pathcch.h中找到。 PathCchRemoveFileSpec将删除路径中的最后一个元素,因此,如果您传递的是目录路径,则最后一个文件夹将被剥离。
如果您想避免这种情况,并且不确定文件路径是否为目录,请使用PathIsDirectoryPathCchRemoveFileSpec在包含正斜杠的路径上的行为与预期不符。

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
}

5
如果是正斜杠(/)呢? - Cameron

2
假设您可以使用C++17,代码应该如下所示:
std::filesystem::path fullpath(path_string);
fullpath.remove_filename();
cout << fullpath.string();

如果您没有使用c++17,但可以访问boost库,则可以使用boost::filesystem::path完成相同的操作。

使用这些库的优点是与多个操作系统兼容。


1
这是最佳答案,因为它与操作系统无关。 - Mr Squid

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接