C: 用 fgets() 替换 gets() 时出错
C: error replacing gets() with fgets()
我目前在用 fgets() 替换 gets() 时遇到问题。我看过多个这样做的例子,它看起来非常简单,但是我在这样做时得到了意想不到的输出。在下面的评论中使用 gets() 方法,我从我正在编写的 shell 程序中获得了良好的行为,但是当我更改为 fgets() 调用时,我得到输出“:没有这样的文件或目录”输入 "ls"。就像我说的,使用 gets() 调用它工作正常。代码如下:
int main(void) {
while(1) {
int i = 0;
printf("$shell: ");
scanf("%s", first);
/* gets(input);*/
fgets(input, sizeof(input), stdin);
//...parse input into tokens for exec system call...
execvp(first, args);
}
return 0;
}
与gets
不同,fgets
会读取换行符并将其存储在字符串中。
来自手册页:
fgets()
reads in at most one less than size characters from stream
and stores them into the buffer pointed to by s. Reading stops
after an EOF
or a newline. If a newline is read, it is stored into
the buffer. A '[=15=]'
is stored after the last character in the
buffer.
您可以通过将换行符替换为空字节来删除换行符(如果存在):
fgets(input, sizeof(input), stdin);
if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '[=10=]';
我目前在用 fgets() 替换 gets() 时遇到问题。我看过多个这样做的例子,它看起来非常简单,但是我在这样做时得到了意想不到的输出。在下面的评论中使用 gets() 方法,我从我正在编写的 shell 程序中获得了良好的行为,但是当我更改为 fgets() 调用时,我得到输出“:没有这样的文件或目录”输入 "ls"。就像我说的,使用 gets() 调用它工作正常。代码如下:
int main(void) {
while(1) {
int i = 0;
printf("$shell: ");
scanf("%s", first);
/* gets(input);*/
fgets(input, sizeof(input), stdin);
//...parse input into tokens for exec system call...
execvp(first, args);
}
return 0;
}
与gets
不同,fgets
会读取换行符并将其存储在字符串中。
来自手册页:
fgets()
reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after anEOF
or a newline. If a newline is read, it is stored into the buffer. A'[=15=]'
is stored after the last character in the buffer.
您可以通过将换行符替换为空字节来删除换行符(如果存在):
fgets(input, sizeof(input), stdin);
if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '[=10=]';