0

Here is my code:

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

int main() {
    printf("hello");
    sleep(1);
    fflush(stdout);
    printf("\rworld");
    sleep(1);
    fflush(stdout);
    printf("\r!    \n");
    sleep(1);
    return 0;
}

It displays "Hello" for a second, does nothing for another second, and then goes straight to "!" I have tried to change the sleep durations and a few other things but nothing has fixed it. What am I doing wrong?

  • 3
    Did you try flushing directly after your printf s rather than before them? It isn't skipping your printf s Its just not necessrily on the screen for very long before you overwrite it. – Avi Berger Sep 25 '22 at 20:15
  • Yes, if you wait until just before the next output you may not even see it, if it overwrites it. – Weather Vane Sep 25 '22 at 20:19
  • @AviBerger Thanks! Switching the fflush and sleep fixed the issue! – Anivartin Anand Sep 25 '22 at 20:20
  • You could try `fprintf( stderr, "Hello" );` as (I believe) `stderr` is not buffered. No need for the calls to `flush()`... Just a thought. – Fe2O3 Sep 25 '22 at 22:18

1 Answers1

0

Flush before sleep to insure timely display.

stdout buffering mechanisms are implementation defined. Yet fflush() will get the output done promptly.

int main(void) {
    printf("hello");
    fflush(stdout);
    sleep(1);

    printf("\rworld");
    fflush(stdout);
    sleep(1);

    printf("\r!    \n");
    fflush(stdout);
    sleep(1);

    return 0;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256