Search code examples
cdelay

How to use the \r carriage return character with a delay in C programming?


I am getting started with C programming and I am trying to solve a practice lesson in the book I am learning from. The task I need to do is to print a line to the terminal then wait 2 seconds and after 2 seconds return the cursor to the beginning of the line in the terminal and replace, overwrite the line with something else.

The example code in the book contain lots of boilerplate code for other tasks I also need to do, for now I am trying to isolate and solve this first problem on its own, but it does not work and I don't understand why.

This is the code I'm trying:

#include "stdio.h"
#include "time.h"

int main() {

  const int DELAY = 2;
  time_t wait_start = 0;

  printf("We print this then wait 2 seconds");

  //delay by repeating this empty for loop
  wait_start = clock(); //the time when we start the delay and subtract this from the current time returned by clock()
  for ( ; clock() - wait_start < DELAY * CLOCKS_PER_SEC; );

  printf("\r");
  printf("We did return the cursor to the beginning and print this after 2 seconds");

  return 0;
}

What I would like to happen is to print the first line, wait 2 seconds and then overwrite, replace the first line with the second line.

However, when I execute this code, despite the delay, it seems it returns the cursor to the beginning of the line immediately, and it does not print the first line in to the terminal, but after 2 seconds it doesn't print the second line.

Could someone please help and explain to me why is this happening and how to solve it?

Thank you.


Solution

  • When you use printf, you write to the stdout buffer. It does not have to be displayed immediately, unless you flush it (using fflush()) or you write a newline (\n) character, which effectively flushes it.