c ++如何从路径字符串中删除文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10364877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ how to remove filename from path string
提问by Mat
I have
我有
const char *pathname = "..\somepath\somemorepath\somefile.ext";
how to transform that into
如何将其转化为
"..\somepath\somemorepath"
?
?
回答by dasblinkenlight
The easiest way is to use find_last_of
member function of std::string
最简单的方法是使用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;
This solution works with both forward and back slashes.
此解决方案适用于正斜杠和反斜杠。
回答by acraig5075
On Windows use _splitpath()
and on Linux use dirname()
在 Windows 上使用_splitpath()
和在 Linux 上使用dirname()
回答by roob
On Windows 8, use PathCchRemoveFileSpec
which can be found in Pathcch.h
在 Windows 8 上,使用PathCchRemoveFileSpec
可以在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
将删除路径中的最后一个元素,因此如果向它传递目录路径,最后一个文件夹将被删除。
如果您想避免这种情况,并且不确定文件路径是否为目录,请使用PathIsDirectory
PathCchRemoveFileSpec
does not behave as expected on paths containing forwards slashes.
PathCchRemoveFileSpec
在包含正斜杠的路径上的行为不符合预期。
回答by Not_a_Golfer
use strrchr()
to find the last backslash and strip the string.
用于strrchr()
查找最后一个反斜杠并去除字符串。
char *pos = strrchr(pathname, '\');
if (pos != NULL) {
*pos = '##代码##'; //this will put the null terminator here. you can also copy to another string if you want
}
回答by Justin
PathRemoveFileSpec(...) you dont need windows 8 for this. you will need to include Shlwapi.h and Shlwapi.lib but they are winapi so you dont need any special SDK
PathRemoveFileSpec(...) 为此,您不需要 Windows 8。你需要包含 Shlwapi.h 和 Shlwapi.lib 但它们是 winapi 所以你不需要任何特殊的 SDK