繁体   English   中英

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

[英]c++ how to remove filename from path string

我有

const char *pathname = "..\somepath\somemorepath\somefile.ext";

如何将其转换为

"..\somepath\somemorepath"

?

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

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

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

在Windows 8中,使用PathCchRemoveFileSpec它可以发现Pathcch.h

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

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

使用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
}

PathRemoveFileSpec(...) 你不需要 windows 8 为此。 你需要包括 Shlwapi.h 和 Shlwapi.lib 但它们是 winapi 所以你不需要任何特殊的 SDK

假设您可以访问 c++17 它应该是这样的:

std::filesystem::path fullpath(path_string);
fullpath.remove_filename();
cout << fullpath.string();

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

使用这些库之一具有与多个操作系统兼容的优点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM