简体   繁体   English

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

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

I have我有

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

how to transform that into如何将其转换为

"..\somepath\somemorepath"

? ?

The easiest way is to use find_last_of member function of std::string 最简单的方法是使用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;

This solution works with both forward and back slashes. 此解决方案适用于正斜杠和反斜杠。

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

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. PathCchRemoveFileSpec将删除路径中的最后一个元素,因此如果将目标路径传递给它,则将剥离最后一个文件夹。
If you would like to avoid this, and you are unsure if a file path is a directory, use PathIsDirectory 如果您想避免这种情况,并且不确定文件路径是否是目录,请使用PathIsDirectory

PathCchRemoveFileSpec does not behave as expected on paths containing forwards slashes. PathCchRemoveFileSpec在包含转发斜杠的路径上的行为不正常。

use strrchr() to find the last backslash and strip the string. 使用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(...) you dont need windows 8 for this. PathRemoveFileSpec(...) 你不需要 windows 8 为此。 you will need to include Shlwapi.h and Shlwapi.lib but they are winapi so you dont need any special SDK你需要包括 Shlwapi.h 和 Shlwapi.lib 但它们是 winapi 所以你不需要任何特殊的 SDK

Supposing you have access to c++17 it should be something like this:假设您可以访问 c++17 它应该是这样的:

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

If you don't have c++17, but have access to boost, you can do the same thing with boost::filesystem::path.如果您没有 c++17,但可以访问 boost,您可以使用 boost::filesystem::path 执行相同的操作。

Using one of these libraries has the advantage of being compatible with multiple operating systems.使用这些库之一具有与多个操作系统兼容的优点。

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

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