1

Coming from here: https://stackoverflow.com/a/1716621/1461017

I want to print separate points (dots, "."), one at a time on the same line, under control of a for loop:

for (i=0; i<100; i++)
{
    printf(".");
    sleep(1);
}
printf("\n");

But the output only goes to screen after the final "\n", and I want each one to display immediately upon printing, so as to serve as progress indicators. I expected that fflush()ing the standard output on each loop iteration would produce that result, but this does not work (results are only shown on screen after the execution of the for loop):

for (i=0; i<100; i++)
{
    printf(".");
    sleep(1);
    fflush(stdout);
}
printf("\n");

I have furthermore tested all of these approaches, both in and out of the loop, with no success:

fflush(stdout);
fflush(NULL);
setbuf(stdout,NULL);

What is going on here, and how can I solve it?

Further Data:

  • Ubuntu Linux v16 as operating system.
  • Code::Blocks as IDE.
  • Problem only happens when running on Bash command line. Working OK inside the IDE.
  • Tested on Ubuntu Linux (same that runs the IDE) and FreeBSD (via cross compiling with clang).
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
Sopalajo de Arrierez
  • 2,991
  • 4
  • 28
  • 42

1 Answers1

0

Well... a stupid issue, but I think I should write it down anyway, because someone could have it too:

The problem was: on the command-line testing, I appended some | more in order to stop the screen dumping. So the stdout buffer was altered by the piping | command.

Say my program binary file was named dotting. I called it by typing:

dotting | more

I hope this ridiculous case could help anyone in a future.

Sopalajo de Arrierez
  • 2,991
  • 4
  • 28
  • 42