Reputation: 6196
My question pertains to using a file descriptor which could be stdin or an opened file.
I am trying to figure out:
cin >> x
wait for user input, but fgets(line, len, file)
on an opened file never stalls to my knowledge. (I know stalling would not make sense for reading a file, but I'm trying to figure out how streams work here.)Upvotes: 0
Views: 130
Reputation: 490538
Fundamentally there's no difference between reading using cin
(or another istream
) vs. fgets
(or fscanf
, etc.)
In both cases, if you read from standard input, they'll stall waiting for input, and return EOF when they receive the correct indication that standard input has reached end of file (e.g., ctrl+d on Linux, ctrl+z or F6 on Windows). Of course, if standard input is redirected to a file, the program will sense end of file just like it normally would.
Likewise, in both cases, they actually are stalling while reading data from a file on disk--but at least in a typical case, the still be on the order of tens of milliseconds, so a person typically won't perceive it. Nonetheless, yes, when the CPU issues a read command to the drive controller, there's an extremely long pause (in terms of number of CPU clock cycles) before the data arrives from the disk drive. In a few cases, you can get long enough delays when reading from a file that they become human perceptible, or could even involve human intervention. It's pretty rare now, but once upon a time, reading a particular file could involve something like an operator mounting a tape.
Upvotes: 3