1

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:

  1. printf does not always flush. (See duplicate)
  2. std::endl forces a newline as well as a call to flush.
Daniel
  • 428
  • 3
  • 8
  • 5
    It's not `cout`, [it's `endl`](https://accu.org/index.php/journals/2619)! – BoBTFish Jul 07 '20 at 13:49
  • 4
    Does this answer your question? [Does printf always flush the buffer on encountering a newline?](https://stackoverflow.com/questions/5229096/does-printf-always-flush-the-buffer-on-encountering-a-newline) A pipe will be an "interactive device", afaict. – underscore_d Jul 07 '20 at 13:52
  • 1
    Will be closed as a duplicate but tl;dr; `fflush(stdout);` – Ted Lyngmo Jul 07 '20 at 13:53
  • _"As far as I know, printf() should flush its buffers when it encounters a \n character."_ According to what? Don't make assumptions!! – Asteroids With Wings Jul 07 '20 at 14:24

0 Answers0