gpt4 book ai didi

在 C 程序中更改 Linux shell 中的工作目录

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:27 25 4
gpt4 key购买 nike

我的目标是编写一个类似于 Linux 基本 shell 的 C 程序。除了更改工作目录外,我一切正常。我已尝试使用 system()cd 输入字符串,但没有任何反应。我也试过 chdir("tokened string") 也没有成功。有人有主意吗?这是我的代码的一部分:

        fgets(cmdStr, sizeof(cmdStr), stdin);

if( strncmp("quit", cmdStr, 4) == 0 || strncmp("Quit", cmdStr, 4) == 0 )
{
break;
}
else if( strncmp("cd", cmdStr, 2) == 0 )
{
char *token = strtok(cmdStr, " ");
token = strtok(NULL, " ");
chdir(token);
}
else
{
system(cmdStr);
}
}

这有可能吗?或者这是与子 shell 无法执行某些操作有关的简单情况?

编辑:上面的代码是完整的。

最佳答案

fgets()cmdstr 中留下尾随的 '\n' 字符。

如果您键入 cd foo,您将调用 chdir("foo\n") 而不是 chdir("foo") .

关于在 C 程序中更改 Linux shell 中的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920483/

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