[代码实例][Linux系统编程]相对路径转绝对路径

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

#include <unistd.h>
#include <limits.h>

#define MIN(x,y)    (((x) < (y)) ? (x) : (y))

char * rpath_to_apath(const char * rpath, char * buf, int buf_size);

int main(int argc, char * argv[])
{
    char * rpath = NULL;
    char * apath = NULL;

    if((argc == 2 && strcmp(argv[1], "--help") == 0)
        || argc > 2)
    {
        printf("Usage: %s <relative_path>\n", argv[0]);
        return EXIT_SUCCESS;
    }

    if(argc == 1)
        rpath = "./";
    else
        rpath = argv[1];

    if(rpath[0] == '/')
    {
        fprintf(stderr, "path must be relative path!\n");
        return EXIT_FAILURE;
    }
    printf("relative path: %s\n", rpath);

    if((apath = malloc(PATH_MAX)) == NULL)
    {
        perror("malloc");
        return EXIT_FAILURE;
    }
    memset(apath, 0, PATH_MAX);

    printf("absolute path: %s\n", rpath_to_apath(rpath, apath, PATH_MAX));
    free(apath);

    return EXIT_SUCCESS;
}

char * rpath_to_apath(const char * rpath, char * buf, int buf_size)
{
    char cur_work_dir[PATH_MAX] = {0};
    int index = 0;
    const char * p = rpath;

    while(*p == '.')
        p++;
    if(*p == '/')
        p++;

    if(getcwd(cur_work_dir, PATH_MAX) == NULL)
    {
        perror("getcwd");
        return NULL;
    }

    index = strlen(strncpy(buf, cur_work_dir, buf_size - 1));
    if(*p)
    {
        buf[index] = '/';
        strncpy(buf + index + 1, p,
                MIN(strlen(p), (buf_size - 1) - (index + 1)));
    }

    return buf;
}

这段代码仅仅是实现相对路径和绝对路径之间的转换,但其中存在一个BUG:代码严重依赖于当前工作目录。
正确的做法是调用系统调用realpath():

#include <stdlib.h>
char * realpath(const char * pathname, char * resolved_path);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值