2014-12-11 124 views
0

快速問題:我想在最後一個「/」分割字符串文本(文件路徑)。標識符後分割C字符串

所以,從這個:"/folder/new/new2/new3" 這個作爲結果:"/folder/new/new2"

所以基本上,我總是希望得到的結果是所提供的絕對路徑後面的一個目錄。

我一直在使用strtok一個類似於此得到最後的目錄,但我不知道一個簡單的方法來獲得秒持續目錄。 :

char *last 
    char *tok = strtok(dirPath, "/"); 
    while (tok != NULL) 
    { 
     last=tok; 
     tok = strtok(NULL, "/"); 
    } 
+0

嗨,我沒有。我只是看着它,這可以完美地工作。我可以得到最後一個「/」的索引,然後在那裏分割字符串。我是C新手,所以其中一些功能對我來說是新的。謝謝! – 2014-12-11 01:21:36

+0

http://www.cplusplus.com/reference/clibrary/是一個很好的資源。它是一個C++網站,但它對C庫有很好的文檔。 – dconman 2014-12-11 01:34:15

+0

下面提供了答案,解釋路徑名稱中的尾部斜線。 – DevNull 2014-12-11 01:47:17

回答

4

在參照user3121023的建議我用strrchr,然後置於一個空終止代替最後存在的‘/’的。

char str[] = "/folder/cat/hat/mat/ran/fan"; 
char * pch; 
pch=strrchr(str,'/'); 
printf ("Last occurence of '/' found at %d \n",pch-str+1); 
str[pch-str] = '\0'; 
printf("%s",str); 

這個工作完美,打印的結果是「/文件夾/貓/帽/墊/跑」。

+1

如果路徑有斜線,則失敗。根據情況,兩個結尾斜槓(即:符號鏈接目錄遍歷)是一種有效的方案。 – DevNull 2014-12-11 01:46:45

+0

我正在使用它來創建我正在創建的虛擬FAT文件系統。不會有任何尾隨的斜槓。雖然對於一般應用程序有效。 – 2014-12-11 01:48:39

+1

根據您的路徑字符串生成完成情況,在任何情況下都可能有單個尾部斜線。 http://unix.stackexchange.com/questions/1910/how-linux-handles-multiple-path-separators-home-username-file – DevNull 2014-12-11 02:06:27

0

我在直C上生鏽了,但是在這裏。類似於現有代碼的循環通過使用strstr而不是strtok來查找最後一個斜槓的位置。從那裏只需要將字符串的一部分複製到該斜線。你也可以改變dirPath到位用一個空終止覆蓋最後的斜線,但這種情況可能導致內存泄漏(?),這取決於你的代碼做什麼其他...

// find last slash 
char *position = strstr(dirPath, "/"); 
while (strstr(position, "/") != NULL) 
{ 
    position = strstr(position, "/"); 
} 

// now "position" points at the last slash character 
if(position) { 
    char *answer = malloc(position - dirPath); // difference in POINTERS 
    strncpy(answer, dirPath, position - dirPath); 
    answer[position - dirPath] = `\0`; // null-terminate the result 
} 
0

我沒有編譯並運行。只是爲了好玩。

char* p = dirPath, *last = NULL; 
for(; *p; p++) 
{ 
    if (*p == '/') 
     last = p; 
} 

if (last) 
{ 
    *last = 0; 
    puts(dirPath); 
}