Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;如何从路径字符串中删除文件名_C++_String_Filesystems - Fatal编程技术网

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,所以你不需要任何特殊的SDK

Boost有一个很好的
文件系统::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;