C++ c++;如何从路径字符串中删除文件名
我有 如何将其转化为C++ c++;如何从路径字符串中删除文件名,c++,string,filesystems,C++,String,Filesystems,我有 如何将其转化为 const char *pathname = "..\somepath\somemorepath\somefile.ext"; ?使用strrchr()查找最后一个反斜杠并去除字符串 "..\somepath\somemorepath" 在Windows和Linux上使用最简单的方法是使用std::string的成员函数 char *pos = strrchr(pathname, '\\'); if (pos != NULL) { *pos = '\0'; //t
const char *pathname = "..\somepath\somemorepath\somefile.ext";
?使用strrchr()
查找最后一个反斜杠并去除字符串
"..\somepath\somemorepath"
在Windows和Linux上使用最简单的方法是使用std::string的成员函数
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
}
strings1(“../somepath/somemorepath/somefile.ext”);
字符串s2(“..\\somepath\\somemorepath\\somefile.ext”);
cout在Windows 8上,使用可在Pathcch.h
将删除路径中的最后一个元素,因此如果向其传递目录路径,最后一个文件夹将被剥离。
如果要避免这种情况,并且不确定文件路径是否为目录,请使用
在包含正向斜杠的路径上行为不符合预期。PathRemoveFileSpec(…)您不需要windows 8。
您需要包括Shlwapi.h和Shlwapi.lib
但是它们是winapi,所以你不需要任何特殊的SDKBoost有一个很好的文件系统::path
类…如果它是一个正斜杠(/
),那会怎么样?它可以工作,假设用户从未将任何合法的斜杠放进他的文件名中。这对我不起作用,但这确实起作用
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;