簡體   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