1

The program below prompts the user to input something. If the input is acceptable to fgets, the program will print what the user had input. The program works, except that something strange happens when the user presses Ctrld at the prompt. When the user presses Ctrld at the prompt, the program enters an infinite loop where the prompt gets printed over and over again. Why does this happen?

#include <stdio.h>
#define BUFSIZE 512

int main(void)
{
    char input_buf[BUFSIZE];
    char *user_input;
    while (1) {
        user_input = NULL;
        printf("Input: ");  /* Prompt. */
        if ((user_input = fgets(input_buf, BUFSIZE, stdin)) == NULL) {
            printf("Invalid input. Try again.\n");
            continue;
        } else {
            printf("User input: %s", user_input);
            break;
        }
    }
    return 0;
}
Flux
  • 9,805
  • 5
  • 46
  • 92

1 Answers1

2

If you want to continue reading (or trying to) after an apparent end of file, insert clearerr(stdin); before continue;.

Pressing Control-D in a Unix system with default terminal settings sends whatever the user has currently typed to the process. If the user has not typed anything new (which happens when Control-D is pressed at the beginning of a line or just after another Control-D), the process receives zero characters, and the C stream software treats this as a soft end-of-file indication.

Then further I/O attempts on the stream report end-of-file until you clear the “error.”

(Further information on what Control-D does is here.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312