When I redirect a file to stdin
using MyProgram < cl.txt
command from the command line, scanf
s 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With