gpt4 book ai didi

c - c 中 chdir 的奇怪错误

转载 作者:行者123 更新时间:2023-11-30 18:20:01 25 4
gpt4 key购买 nike

构建一个像 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 a printf is wrong (since a failed printf would change errno).

因此您应该使用上面的fprintf

关于c - c 中 chdir 的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33721774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com