1

I want to print a sequence of characters one by one in the same place. I print one letter, then wait 1 second with sleep, move cursor one column left using console code, print next letter and so on. The problem is as a result program waits the sum of all sleeps (2s in my example) and then prints only the last character ('y'). Same goes with nanosleep, waiting for a signal instead of sleeping. How to make it work?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    printf( "H" );
    sleep( 1 );
    printf( "\033[1D" );
    printf( "e" );
    sleep( 1 );
    printf( "\033[1D" );
    printf( "y" );
}
jww
  • 97,681
  • 90
  • 411
  • 885
Arus23
  • 89
  • 6
  • 3
    buffering, use `fflush(stdout);` after each `printf()` (or at least before each `sleep()`) – Ctx Dec 11 '19 at 11:50
  • 3
    If `fflush()` looks too clumsy, you can also `setvbuf(stdout, NULL, _IONBF, 0);` before the first `printf()`. – Ctx Dec 11 '19 at 11:54
  • 2
    Possible duplicate of [Why does printf() not print anything before sleep()?](https://stackoverflow.com/q/338273/608639), [Printf and sleep inside for loop?](https://stackoverflow.com/q/25627535/608639) and friends. Also see [Why does printf not flush after the call unless a newline is in the format string?](https://stackoverflow.com/q/1716296/608639) – jww Dec 11 '19 at 13:51

1 Answers1

5

Output to stdout (which is where printf writes) is by default (when connected to a terminal) line buffered. That means output is flushed (actually written to the terminal) either when the buffer is full, when you print a newline, or when you explicitly flush it (with fflush).

In your case, since you never fill the buffer and don't print newlines, you need to explicitly call fflush(stdout) before each call to sleep.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621