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

Mat*_*Mat 24 c++ filesystems string

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";
Run Code Online (Sandbox Code Playgroud)

如何将其转化为

"..\somepath\somemorepath"
Run Code Online (Sandbox Code Playgroud)

das*_*ght 45

最简单的方法是使用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;
Run Code Online (Sandbox Code Playgroud)

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

  • 假设用户永远不会将任何斜杠合法地放入他的文件名中 (6认同)

acr*_*075 9

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


roo*_*oob 6

在Windows 8上,使用PathCchRemoveFileSpec可以找到的Pathcch.h

PathCchRemoveFileSpec将删除路径中的最后一个元素,因此如果您将目录路径传递给它,则将删除最后一个文件夹.
如果您想避免这种情况,并且不确定文件路径是否是目录,请使用PathIsDirectory

PathCchRemoveFileSpec 在包含转发斜杠的路径上的行为不正常.