Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does scanf determine whether to block?

When I redirect a file to stdin using MyProgram < cl.txt command from the command line, scanfs doesn't wait me to press Enter.

But when I use scanf in my program without doing so, it does block until enter key is pressed.

How exactly does it determine that? Does it keep reading the stream until \n is encountered? or does it really wait me to press a key?

When I don't write anything and press Enter it doesn't stop blocking either and keeps asking. I'm really confused.

like image 461
Millo Varantz Avatar asked May 23 '15 06:05

Millo Varantz


1 Answers

Does it keep reading the stream until '\n' is encountered?

Normally stdin is in line buffering mode (_IOLBF, see setvbuf). Whenever the buffer is empty, stdin waits for a whole new line to be entered, i.e. waits until you press Enter and \n is inserted into the buffer:

On Input, the buffer is filled up to the next newline character when an input operation is requested and the buffer is empty.

Note: the console (terminal) is most often implementing a buffering on its own, and does not send any data to the stream until you press Enter - this allows you to edit the data (like use delete, and backspace keys) before you send them to the application. Therefore even with no buffering on the stdin side (like when you perform setvbuf(stdin, NULL, _IONBF, 0)), the scanf may still wait until the Enter is pressed.

like image 183
Suma Avatar answered Sep 25 '22 00:09

Suma