Search code examples
cfgets

fgets in infinite loop terminating


I am trying to use fgets within an infinite loop as I need a specific input from the user. I want to continuously print something until I receive any input from the user. However fgets seems to make the program wait for input.

I've tried using other input methods such as gets.

while(1){
        char input[100];
        fgets(input, sizeof(input),stdin);
        printf("I want this statement to continuously print.");
}

The statement only prints when I enter text. However I want it to continuously print the statement regardless of input.


Solution

  • All I/O in the C standard library is blocking I/O. That means if you read from or write to a file (or stdin, etc.), the read or write function will not return until the read or write takes place (or encounters an error).

    If you want to have code execute while I/O operations are going on, you need to either (1) use multiple threads, or (2) use low-level non-blocking I/O (for example, Posix read/write to files with O_NONBLOCK). With stdin, this may also involve some low-level messing with terminal settings.