c - 在 C 中拆分路径字符串

标签 c path filesystems

假设我有一个字符串中的文件路径(作为我的函数的参数),如下所示:

"foo/foobar/file.txt"

foofoobar 是目录

我将如何拆分此路径文件,以便我拥有如下所示的这些字符串?:

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

最佳答案

“strtok”被认为是不安全的。您可以在此处找到有关它的更多详细信息:

Why is strtok() Considered Unsafe?

因此,除了使用 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/

相关文章:

javascript - 为 asm.js 编写优化的 JS

node.js - Nodejs + Handlebars - 拉取当前 url 路径并传递给 Helper

path - 完美水平路径的 SVG 渐变

c++ - 使用 C++ 将文件和目录从一个目录递归复制到另一个目录时,不会保留软链接(soft link)

java - Hadoop 文件系统中目录的路径是什么?

我看不懂的C代码

谁能用C语言解释一下这段小代码?

linux - 为什么 Linux 启动时会为根目录 "/"初始化一些 dentry

计算数组中的位数并显示它们,然后将其乘以给定数字

macos - 如何在 Mac OS 上的 XAMPP 下运行 mysqldump