Given the following two programs:
// Printf Version
#include <iostream>
#include <unistd.h>
int main()
{
printf("A: hello 1 \n");
printf("A: hello 2 \n");
printf("A: hello 3 \n");
sleep(100);
}
// cout version
#include <iostream>
#include <unistd.h>
int main()
{
std::cout << "A: hello 1" << std::endl;
std::cout << "A: hello 2" << std::endl;
std::cout << "A: hello 3" << std::endl;
sleep(100);
}
If these programs are run, the output is as expected:
> ./printf_main
A: hello 1
A: hello 2
A: hello 3
Same for the cout version. If, however, I grep the output of these programs, I see no output for the printf version, but output works fine for the std::cout version. In the printf version, I only see the output when the timer expires and the program terminates.
> ./printf_main | grep A
// Not output here!
> ./cout_main | grep A
A: hello 1
A: hello 2
A: hello 3
What is going on here? As far as I know, printf() should flush its buffers when it encounters a \n character.
Are there differences in the implementations of printf/std::cout ??
I know I could just use std::cout, but the question is more academical. I am qurious as to what is going on underneath.
EDIT: Solution is two-fold:
- printf does not always flush. (See duplicate)
- std::endl forces a newline as well as a call to flush.