c语言去除linux路径中的相对符号(. ..)

#include <stdio.h>

static inline void absolute_path_clean(char *path, int len)
{
    int i;
    char *p, *q;
    p = path;
    for (i=1; i<len; i++)
    {
        if (path[i] == '/')
        {
            q = path +i;
            if (q == p + 1)
            {
                // 连续二个/
                char *r = q;
                while (r < path + len)
                {
                    char *t = r - q + p;
                    *t = *r;
                    r++;
                }
                path[len-(int)(q-p)] = 0;

                i = i - 1;
                len = len - 1;
                q = p;
            }
            else if ((q == p+2) && (p[1] == '.'))
            {
                // 本级路径为.
                char *r = q;
                while (r < path + len)
                {
                    char *t = r - q + p;
                    *t = *r;
                    r++;
                }
                path[len-(int)(q-p)] = 0;

                i = i - 2;
                len = len - 2;
                q = p;
            }
            else if ((q == p+3) && (p[1] == '.') && (p[2] == '.'))
            {
                // 本级路径为..
                char *r = q;
                // 找出p的上一个/
                while (p > path)
                {
                    p--;
                    if (*p == '/')
                    {
                        break;
                    }
                }

                while (r < path + len)
                {
                    char *t = r - q + p;
                    *t = *r;
                    r++;
                }
                path[len-(int)(q-p)] = 0;

                i = i - (int)(q-p);
                len = len - (int)(q-p);
                q = p;
            }

            p = q;
        }
    }
}

int main()
{
	char buf[1024] = {0};
	char *path = "//home/../../a/./bb";
	strcpy(buf, path);
	absolute_path_clean(buf, 1024);
	printf("before: %s ,after: %s\n", path, buf);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值