Joh*_*nyF -1 c unix linux chdir
像prog一样建造一个小壳
我尝试制作cd命令,所以我使用:
if (!strcmp(cmd, "cd") )
{
if(chdir("args[1]")!=0){
printf(" %s - path not found\n",args[1]);
perror("Error:");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
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
Run Code Online (Sandbox Code Playgroud)
ps工作目录中有一个"test"文件夹
也许你们可以帮助我如何制作"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));
}
}
Run Code Online (Sandbox Code Playgroud)
从printf您的路径输出似乎没问题,注意printf你没有,"args[1]"但你有args[1].
@BasileStarynkevitch在下面的评论中也指出:
perror在printf错误之后(因为失败printf会改变errno).
因此你应该使用fprintf上述内容.