在 C 程序中更改 Linux shell 中的工作目录 [英] Changing working directories in Linux shell in a C program
问题描述
我的目标是编写一个类似于 Linux 基本 shell 的 C 程序.除了更改工作目录外,我一切正常.我已经尝试了 system()
用于 cd
的输入字符串,但没有任何反应.我也试过 chdir("tokened string")
也没有运气.有人有想法么?这是我的代码的一部分:
My goal is to write a C program that is like a basic shell for Linux. I have everything working except changing working directories. I have tried the system()
for input strings for cd
and nothing happened. I also tried chdir("tokened string")
and also no luck. Anyone have any ideas? This is part of my code:
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 无法做某些事情有关?
Is it possible to do this? Or is this a simple case of something to do with the child shell not being able to do certain things?
上面的代码是完整的.
推荐答案
fgets()
在 cmdstr
中留下尾随的 '
'
字符>.
fgets()
leaves the trailing '
'
character in cmdstr
.
如果你输入 cd foo
,你会调用 chdir("foo
")
而不是 chdir("foo")
.
If you type cd foo
, you'll call chdir("foo
")
rather than chdir("foo")
.
这篇关于在 C 程序中更改 Linux shell 中的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!