Linux 路徑壓縮,去除../和./

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

// 最多128層
int path_compress(char * str) {
    int stack[128];
    int sssss[128];
    int i, si = 0;
    int m, n, ret;
    char *node;
    struct stat statbuf;

    puts(str);
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] == '/') {
            str[i] = 0;
            stack[si] = i+1;
            si++;
        }
    }

    memset(sssss, 0, sizeof(sssss));
    for (i = 0, m = 0; i < si; i++) {
        node = (&str[stack[i]]);
        if (node[0] == '.') {
            if (node[1] == '.')
            {
                sssss[m-1] = 0;
                m--;
            }
            else if (node[1] != '\0') {
                sssss[m++] = stack[i];
            }
        }
        else if (node[0] != '\0') {
            sssss[m++] = stack[i];
        }
    }
    for (i = 0, n = 0; i < m; i++) {
        node = (&str[sssss[i]]);
        n += sprintf(str+n, "/%s", node);
    }
    str[n] = 0;

    ret = lstat(str, &statbuf);
    if (ret != 0) {
        perror("lstat");
    }
    else {
        if (S_ISDIR(statbuf.st_mode)) {
            str[n] = '/';
            str[n+1] = 0;
        }
    }
    puts(str);
}

int main(int argc, char **argv) {
    char *  path;
    char    buffer[1024];

    if (argc > 1) {
        memset(buffer, 0, sizeof(buffer));
        if (argv[1][0] == '/') {
            sprintf(buffer, "%s", argv[1]);
        }
        else {
            path = getcwd(buffer, sizeof(buffer));
            sprintf(buffer, "%s/%s", path, argv[1]);
        }
        path_compress(buffer);
    }
    return 0;
}

測(cè)試

test1@iStation:~/mymind$ gcc path.c
test1@iStation:~/mymind$ ./a.out ../var//tmp/abc/d/./../abc/123/../../../../2kk/./kk/999/.git
/home/test1/mymind/../var//tmp/abc/d/./../abc/123/../../../../2kk/./kk/999/.git
/home/test1/var/2kk/kk/999/.git
test1@iStation:~/mymind$ ./a.out /var//tmp/abc/d/./../abc/123/../../../../2kk/./kk/999/.git
/var//tmp/abc/d/./../abc/123/../../../../2kk/./kk/999/.git
/var/2kk/kk/999/.git
test1@iStation:~/mymind$
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容