C:使用fgets()替换gets()时出错

时间:2021-05-17 01:46:41

I am currently having an issue replacing gets() with fgets(). I have looked at multiple examples of doing this and it seems very straight forward however I am getting unexpected output in doing so. Using the gets() method in comments below, I get good behavior from my shell program I am writing, however when I change to the fgets() call, I get output ": no such file or directory" when giving input "ls". Like I said, with the gets() call it is working fine. code below:

我目前在使用fgets()替换gets()时遇到问题。我已经看过这样做的多个例子,看起来非常直接,但是这样做会得到意想不到的输出。在下面的注释中使用gets()方法,我从我正在编写的shell程序中得到了良好的行为,但是当我更改为fgets()调用时,在输入“ls”时输出“:no such file or directory” 。就像我说的,使用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;
}

1 个解决方案

#1


2  

Unlike gets, fgets will read the newline and store it in the string.

与gets不同,fgets将读取换行符并将其存储在字符串中。

From the man page:

从手册页:

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 '\0' is stored after the last character in the buffer.

fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。阅读在EOF或换行后停止。如果读取换行符,则将其存储到缓冲区中。在缓冲区中的最后一个字符之后存储'\ 0'。

You can remove the newline (if it is present) by replacing it will a null byte:

您可以通过替换它来删除换行符(如果它存在)将是一个空字节:

fgets(input, sizeof(input), stdin);
if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '\0';

#1


2  

Unlike gets, fgets will read the newline and store it in the string.

与gets不同,fgets将读取换行符并将其存储在字符串中。

From the man page:

从手册页:

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 '\0' is stored after the last character in the buffer.

fgets()从流中读取最多一个小于大小的字符,并将它们存储到s指向的缓冲区中。阅读在EOF或换行后停止。如果读取换行符,则将其存储到缓冲区中。在缓冲区中的最后一个字符之后存储'\ 0'。

You can remove the newline (if it is present) by replacing it will a null byte:

您可以通过替换它来删除换行符(如果它存在)将是一个空字节:

fgets(input, sizeof(input), stdin);
if (input[strlen(input)-1] == '\n') input[strlen(input)-1] = '\0';