c - 使用 strtok() 定界路径

标签 c path strtok

我正在尝试从其路径获取文件。 这是我的代码:

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

char split_path(char *path){

    char *str1, *delim;
    char buf[255];
    int i, max;

    char *token = "/";

    for (i = 1, str1 = path; ; i++, str1 = NULL){
        delim = strtok(str1, token);
        if (delim == NULL){
            break;
        }
        buf[i] = *delim;
        max = i;
    }

    char last = buf[max];

    return last;
}


int main(int argc, char *argv[]){

    if (argc != 3){
        fprintf(stderr, "Usage: %s string delim\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    char last = split_path(argv[1]);

    printf("%c\n", last);

    return 0;
}

因此,如果我输入/a/b/c/d ,它会返回我想要的“d”。 但是如果我输入/a/b/c/d.txt,当我需要的是 'd.txt' 时,它只返回 'd' 而没有 '.txt'。 它似乎只在最后一个/之后获得第一个索引。我似乎无法弄清楚问题所在。 非常感谢帮助。

最佳答案

您的问题是 split_path 正在返回 strtok 的最后一个好结果的第一个字母。

更改 split_path 以返回一个字符串,并稍微修改它......像这样:

    char *split_path(char *path){

    char *str1, *delim;
    int i, max;
    char *last = NULL;

    char *token = "/";

    for (i = 1, str1 = path; ; i++, str1 = NULL){
        delim = strtok(str1, token);
        if (delim == NULL){
            break;
        }
        last = delim;
    }

    return last;
}


int main(int argc, char *argv[]){

    if (argc != 3){
        fprintf(stderr, "Usage: %s string delim\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    char *last = split_path(argv[1]);

    printf("%s\n", last);

    return 0;
}

关于c - 使用 strtok() 定界路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262810/

相关文章:

c - 如何正确更改c中char []中的元素

c - 遍历数组元素会在数组计数器的最后一个值上产生奇怪的值

c - 不兼容的指针不允许将 csv 放置到二维数组中

c - C 中函数维护内部状态

在 C 中将 char * 转换为大写

c - 开关盒奇怪的范围

C 转换和字符符号

python - 如何读取名称困惑且不可读的文件?

python - 将python作为脚本运行时导入失败,但在iPython中没有?

java - 压缩包 "could not find a JVM"