我有
const char *pathname = "..\somepath\somemorepath\somefile.ext";
如何将其转换为"..\somepath\somemorepath"
?
我有
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;
这个解决方案适用于前斜杠和后斜杠。
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
}
/
)呢? - Cameronstd::filesystem::path fullpath(path_string);
fullpath.remove_filename();
cout << fullpath.string();
如果您没有使用c++17,但可以访问boost库,则可以使用boost::filesystem::path完成相同的操作。
使用这些库的优点是与多个操作系统兼容。
PathRemoveFileSpec(...) 这个不需要 Windows 8。 你需要包含 Shlwapi.h 和 Shlwapi.lib 但它们是 WinAPI,所以你不需要任何特殊的 SDK。
filesystem::path
类... - Cameron