ElusiveTau wrote: |
---|
(I suspect there's a system call in the implementation of the library that pauses program execution to accomplish this task).
|
Good call. If you use Linux, you can run your program under strace to observe exactly these system calls. I'll do it below
ElusiveTau wrote: |
---|
Ultimately, I'm trying to get a better idea of what fflush() does and the example doesn't suffice. What would help, I think, is a code example in which you explicitly put garbage in the buffer and use fflush() to clear it.
|
To put garbage somewhere, you have to get garbage from somewhere first.
1 2 3 4 5
|
int main() {
char c; // garbage in a variable
putchar(c); // garbage in the buffer
fflush(stdout); // garbage on the screen.
}
|
But that won't help you see any effect of fflush - as with any proper buffered I/O, the results are the same as if you don't flush it.
What fflush exists for. It's for immediate output on a buffered C I/O stream:
1 2 3 4 5 6 7 8 9 10
|
#include <thread>
#include <chrono>
#include <cstdio>
using namespace std::literals;
int main()
{
printf("stuff");
std::this_thread::sleep_for(10s);
printf("more stuff\n");
}
|
if you run this program, it sits there and waits 10 seconds, and then suddenly prints "stuffmorestuff"
strace will show that the output was in a single system call after the pause
nanosleep({tv_sec=10, tv_nsec=0}, NULL) = 0
write(1, "stuffmore stuff\n", 16) = 16
|
If you change that to
1 2 3 4 5 6 7 8 9 10 11
|
#include <thread>
#include <chrono>
#include <cstdio>
using namespace std::literals;
int main()
{
printf("stuff");
fflush(stdout);
std::this_thread::sleep_for(10s);
printf("more stuff\n");
}
|
then it prints "stuff" instantly, and 10 seconds later adds "more stuff" to the same line.
strace will show the system calls separated by the pause:
write(1, "stuff", 5) = 5
nanosleep({tv_sec=10, tv_nsec=0}, NULL) = 0
write(1, "more stuff\n", 11) = 11
|
Note that if you make it
printf("stuff\n");
, the endline will flush stdout (by default) and there would be no difference.. now you would have to learn about three buffering strategies used by the C I/O streams - see
setbuf
/
setvbuf
if you're that adventurous. One thing for certain,
fflush(stdin)
is nonsense (except when working with POSIX files that change under your feet).