在linux壳牌在C程序更改工作目录 [英] Changing Working Directories in linux shell in a C Program
问题描述
好了,所以我的目标是写一个C程序就像是Linux的一个基本的shell。我除了改变工作目录一切工作正常。我曾尝试输入字符串system()的CD和什么都没有发生。我也试过CHDIR(tokened串),也没有运气。任何人有什么想法?这是我的code的一部分:
Okay so 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? Thanks!
编辑:code以上完成
Code above is complete.
解决,与fgets增加了\\ n字符串。通过code去了,在tokened串摆脱了\\ n和CD的作品没有问题。感谢大家的帮助。
Solved, fgets adds a \n to the string. Went through the code and got rid of the \n in the tokened string and the cd works without a problem. Thanks for the help everyone.
推荐答案
与fgets()
叶尾随的'\\ n'
字符 cmdstr
。
如果您键入 CD富
,你会打电话给 CHDIR(富\\ n)
,而不是 CHDIR(富)
。
If you type cd foo
, you'll call chdir("foo\n")
rather than chdir("foo")
.
这篇关于在linux壳牌在C程序更改工作目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!