构建一个像 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工作目录中有一个“test”文件夹
pps 也许你们可以帮助我如何制作“cd ..”命令
最佳答案
您正在将实际字符串“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
after aprintf
is wrong (since a failedprintf
would changeerrno
).
因此您应该使用上面的fprintf
。
关于c - c 中 chdir 的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33721774/