假设我有一个字符串中的文件路径(作为我的函数的参数),如下所示:
"foo/foobar/file.txt"
foo
和 foobar
是目录
我将如何拆分此路径文件,以便我拥有如下所示的这些字符串?:
char string1[] = "foo"
char string2[] = "foobar"
char string3[] = "file.txt"
最佳答案
“strtok”被认为是不安全的。您可以在此处找到有关它的更多详细信息:
因此,除了使用 strtok,您可以简单地将“/”替换为“\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”为指针分配更多内存。
关于c - 在 C 中拆分路径字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27261558/