2014-12-03 32 views
1
路徑字符串

說我有一個字符串文件的路徑(作爲參數傳遞給我的函數)如下:分裂用C

"foo/foobar/file.txt" 

foofoobar是目錄

如何我是否會分開這個路徑文件,以便我有如下這些字符串?:

char string1[] = "foo" 
char string2[] = "foobar" 
char string3[] = "file.txt" 
+0

看看'strtok()'。 – alex 2014-12-03 00:28:31

回答

1

「strtok」被認爲是不安全的。你可以在這裏找到更多的細節吧:

Why is strtok() Considered Unsafe?

因此,而不是使用的strtok的,你可以簡單地替換「/」 s的「\ 0',然後使用‘的strdup’分裂路徑。您可以在下面找到實現:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

char **split(char *path, int *size) 
{ 
    char *tmp; 
    char **splitted = NULL; 
    int i, length; 

    if (!path){ 
     goto Exit; 
    } 

    tmp = strdup(path); 
    length = strlen(tmp); 

    *size = 1; 
    for (i = 0; i < length; i++) { 
     if (tmp[i] == '/') { 
      tmp[i] = '\0'; 
      (*size)++; 
     } 
    } 

    splitted = (char **)malloc(*size * sizeof(*splitted)); 
    if (!splitted) { 
     free(tmp); 
     goto Exit; 
    } 

    for (i = 0; i < *size; i++) { 
     splitted[i] = strdup(tmp); 
     tmp += strlen(splitted[i]) + 1; 
    } 
    return splitted; 

Exit: 
    *size = 0; 
    return NULL; 
} 

int main() 
{ 
    int size, i; 
    char **splitted; 

    splitted = split("foo/foobar/file.txt", &size); 

    for (i = 0; i < size; i++) { 
     printf("%d: %s\n", i + 1, splitted[i]); 
    } 

    // TODO: free splitted 
    return 0; 
} 

需要注意的是更好的實現中存在,在路徑上迭代一次,並使用「realloc的」 S在必要時分配更多的內存的指針。