0

I was trying to use the '\r' character to write over the previous line; however, when used in conjunction with nanosleep(), the program does not output until the end. Here is a code example:

int i;
struct timespec t = {1, 0};
for (i = 0; i < 10; ++i) {
    nanosleep(&t, NULL);
    printf('\ri: %d', i);
}

This will wait for 10 seconds, and then print out i: 9. I would like it to show the updates, not just the end. I'm not sure if the line is being flushed or something?

Any and all help is greatly appreciated!

mkel23
  • 105
  • 1
  • 7
  • Read the documentation for `fflush`. – David Schwartz Feb 08 '16 at 21:58
  • 1
    Duplicate: http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – Shloim Feb 08 '16 at 21:59
  • `'\ri: %d'` is a multibyte character constant ; perhaps you meant `"\ri: %d"` – M.M Feb 09 '16 at 02:13
  • @M.M Yes, that is what I meant. The code I was running had double quotes, I mistyped it here when creating the post. – mkel23 Feb 12 '16 at 02:38
  • @DavidSchwartz I was asking specifically if I can do this with `printf()` and if not, why I could not. – mkel23 Feb 12 '16 at 02:39
  • @mkel23 Read your question again. You didn't ask what you think you asked. As I read the question, you asked for an explanation for the behavior you were observing. And nowhere do I see any indication that you're trying to get `printf` specifically to do something. – David Schwartz Feb 12 '16 at 02:42
  • @DavidSchwartz you are correct, my apologies. Had I been clear and concise in the body of my post, there would be less confusion. It is clear now that it is not possible and that I need to use `fflush()`. – mkel23 Feb 12 '16 at 22:58

1 Answers1

1

The console is caching your line until the char \n (newline) appears. You can use "fflush" to explicitly write the content to screen. Maybe there is a little impact on performance.

recycler
  • 611
  • 5
  • 9