C 函数 - cd 表示不起作用

C function - cd representation not working

void cd(char *path) {
    int ret;
    if (strlen (path) > 0) {
        if (path[strlen (path) - 1] == '\n') {
            path[strlen (path) - 1] = '[=10=]';
        }
    }
    ret = chdir(path);
    if(ret == -1) {
        perror("changing directory failed:");
    }
}

这是我的 cd 函数,它应该代表 linux 中 cd 函数的简单版本,如果我想进入一个目录,它可以工作,但如果我想返回,它就不起作用使用 "cd -",有人知道如何解决这个问题吗?

- 不受 C 库 chdir 支持,但仅受 shell cd 命令支持。

要在 C 程序中使用此功能,您必须模拟它。例如,在执行 chdir:

之前存储当前路径
void cd(char *path) {
    int ret;
    // used to store the previous path
    static char old_path[MAX_PATH_LEN] = "";

    if (strlen (path) > 0) {
        if (path[strlen (path) - 1] == '\n') {
            path[strlen (path) - 1] = '[=10=]';
        }
    }
    if (!strcmp(path,"-"))
    {
        // - special argument: use previous path
        if (old_path[0]=='[=10=]')
        {
           // no previous path: error
           return -1;
        }
        path = old_path;  // use previous path
    }
    else
    {   
        // memorize current path prior to changing
        strcpy(old_path,getcwd());
    }
    ret = chdir(path);
    if(ret == -1) {
        perror("changing directory failed:");
    }
}

如果用户使用-两次,可能需要调整,也许可以使用一堆路径,但原理是。