c - c 中 chdir 的奇怪错误

标签 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工作目录中有一个“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/

相关文章:

需要 Cooja 技术信息

linux - EBS 未在亚马逊网络服务中显示正确的磁盘大小

java - Ubuntu 上带 PCSC lite 的 SCL01x 非接触式读卡器

linux - 支持 FIPS 的 OpenSSL 交叉编译 : incore fingerprint issue

检查 C/*nix 中指定用户的文件访问权限

c - 尝试动态选择的菜单..卡在某些部分

c - 如何通过引用将 char * foo[SIZE][SIZE] 传递给函数并取消引用它?

c - 我的输入矩阵不包含零,但是当我打印矩阵时我得到零。问题描述如下

linux - 如何将主目录列表附加到文本文件以及如何移动文件?

python - 从 python 中杀死一个子进程,包括它的子进程