C函数-cd表示不工作

C函数-cd表示不工作,c,linux,cd,C,Linux,Cd,这是我的cd函数,它应该代表linux中cd函数的一个简单版本,如果我想进入目录,它可以工作,但是如果我想返回,使用“cd-”就不起作用,任何知道如何解决这个问题的人?-都不受C库chdir的支持,但只能通过shellcd命令 要在C程序中使用此功能,必须对其进行仿真。例如,在执行chdir之前存储当前路径: void cd(char *path) { int ret; if (strlen (path) > 0) { if (path[strlen (pa

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

-
都不受C库
chdir
的支持,但只能通过shell
cd
命令

要在C程序中使用此功能,必须对其进行仿真。例如,在执行
chdir
之前存储当前路径:

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

如果用户使用
-
两次,可能需要对其进行调整,也许可以使用一堆路径,但原理是存在的。

最终,您会意识到系统调用不支持各种
~
符号或普通
cd
以更改为
$HOME
目录。壳牌也必须管理这些。还可以在POSIX上查找
cd
命令,查看逻辑(
-L
)和物理(
-P
)变体之间的差异。不过,这是以后的事了。为什么要剥离尾随的
'\n'
?我认为这应该是打电话的人的责任。信不信由你,目录名以
'\n'
结尾是完全合法的。此外,如果函数失败,它会将错误消息打印到stderr,但不会通知调用方任何错误。
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] = '\0';
        }
    }
    if (!strcmp(path,"-"))
    {
        // - special argument: use previous path
        if (old_path[0]=='\0')
        {
           // 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:");
    }
}