You need to enable JavaScript to run this app. 在Linux中如何使用strchr函数提取文件路径的上级绝对路径
优惠活动
大模型
产品
解决方案
定价
更多

在Linux中如何使用strchr函数提取文件路径的上级绝对路径

解决方案

错误原因

strchr函数的作用是查找字符串中第一个出现的目标字符,你传入的路径/home/test/sample首字符就是/,所以返回的指针直接指向字符串起始地址,打印结果和原路径完全一致。
要实现上级目录提取,需要找到路径中最后一个出现的/,再截断该位置之后的内容即可。

基于strchr的实现

可以循环调用strchr遍历所有/的位置,记录最后一次匹配的地址再截断:

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

int main() {
    // 将路径存到可修改的字符数组,避免修改只读字符串字面量触发段错误
    char path[] = "/home/test/sample";
    char *cur_slash = strchr(path, '/');
    char *last_slash = NULL;

    // 循环查找所有/,记录最后一次出现的位置
    while (cur_slash != NULL) {
        last_slash = cur_slash;
        cur_slash = strchr(cur_slash + 1, '/');
    }

    // 边界处理
    if (last_slash == path) {
        // 根目录的上级仍为根目录
        printf("/\n");
    } else if (last_slash != NULL) {
        // 截断最后一个/之后的内容
        *last_slash = '\0';
        printf("%s\n", path);
    }

    return 0;
}

运行上述代码输出为/home/test,符合预期。

更简洁的替代实现(Linux标准库支持)

C标准库提供了strrchr函数,可以直接查找字符串中最后一次出现的目标字符,代码更简洁:

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

int main() {
    char path[] = "/home/test/sample";
    char *last_slash = strrchr(path, '/');

    if (last_slash == path) {
        printf("/\n");
    } else if (last_slash != NULL) {
        *last_slash = '\0';
        printf("%s\n", path);
    }

    return 0;
}

额外边界处理

如果输入路径末尾带有/(如/home/test/sample/),可以在查找前先去除末尾所有冗余的/:

int len = strlen(path);
// 仅当路径长度大于1时才删除末尾的/,避免把根目录的/删掉
while (len > 1 && path[len - 1] == '/') {
    path[len - 1] = '\0';
    len--;
}

内容的提问来源于stack exchange,提问作者Pedro Gómez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 14:45:07