我的任务之一是编写自己的UNIX Shell。为了从用户那里接收输入,我使用fgets将输入作为字符串捕获,但我不确定它是如何工作的。当我运行:
char command[50];
fgets(command, sizeof(command), stdin);
printf("Your Command: %s", &command);
int length = strlen(command);
printf("Length of String: %d\n", length);
假设我的输入是"exit"。strlen函数返回字符串长度为5个字符,而不是四个字符。我想要这样做:
if( (strcmp(command, "exit")) == 0 ){
doSomething();
}
但是命令永远不会等于我想要的字符串;就像它有一个未知的字符,我不确定是什么。它是末尾的空字符吗?我该如何更改if语句来检查用户输入是否与fgets捕获的"exit"相等?谢谢!
echo $command|od -a
,它将输出变量内部的每个字符。如果行末有什么奇怪的东西,它也会被显示出来。 - Marc Bstdin
不应该以二进制读取模式打开。 - Chris Lutz