2012-04-28 110 views
20

刪除文件名我有C++如何從路徑字符串

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

如何變換成

"..\somepath\somemorepath" 

+0

Boost有一個不錯的'filesystem :: path'類... – Cameron 2012-04-28 15:27:42

回答

30

最簡單的方法是使用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; 

find_last_of成員函數此解決方案可工作在前進和後退斜線。

+3

它的工作原理假定用戶從不將合法的斜槓放入他的文件名 – Potatoswatter 2012-04-28 15:48:15

+0

適合我:)謝謝! – Mat 2012-04-28 16:17:35

+0

沒有爲我工作,但這確實http://stackoverflow.com/questions/8518743/get-directory-from-file-path-c – brad 2017-01-20 19:29:18

4

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

如果它是正斜槓('/')而不是? – Cameron 2012-04-28 15:29:21