构建像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 .."命令
答案 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
。