问题描述
我的目标是编写一个类似于Linux的基本shell的C程序。除了改变工作目录,我有一切工作。我为 cd
的输入字符串尝试了 system()
,没有发生任何事情。我也尝试过 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()
留下尾随'\\\
' / code>字符 cmdstr
。
如果键入 cd foo
,你会调用 chdir(foo \)
而不是 chdir(foo)
。
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);
}
}
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?
Edit: Code above is complete.
解决方案 fgets()
leaves the trailing '\n'
character in cmdstr
.
If you type cd foo
, you'll call chdir("foo\n")
rather than chdir("foo")
.
这篇关于在C程序中更改Linux shell中的工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!