与chdir的奇怪的臭虫在c

时间:2015-11-15 16:06:03

标签: c linux unix chdir

构建像prog一样的小shell

我尝试制作cd命令,所以我使用:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir("args[1]")!=0){
            printf(" %s - path not found\n",args[1]);
            perror("Error:");
        }
    } 

输出是这样的:

smash > cd /home/johnny/workspace/
 /home/johnny/workspace/ - path not found
Error:: No such file or directory
smash > cd test
 test - path not found
Error:: No such file or directory

ps有一个"测试"工作目录中的文件夹

PPS 也许你们可以帮助我如何制作" cd .."命令

1 个答案:

答案 0 :(得分:7)

您正在将实际字符串"args[1]"传递给chdir。这可能不是你想要的,而是你想要chdir(args[1])所以你的代码看起来像这样:

if (!strcmp(cmd, "cd") ) 
    {
        if(chdir(args[1])!=0){
            fprintf(stderr, "chdir %s failed: %s\n", args[1], strerror(errno));
        }
    } 

printf的输出中,您的路径似乎没问题,请注意printf中您没有"args[1]",而是args[1]

@BasileStarynkevitch在下面的评论中指出:

  perror错误后

printf(因为printf失败了   改变errno)。

因此,您应该使用上面的fprintf