简体   繁体   中英

Print, delay and erase current line in C

I want to print the seconds elapsed in real time since the program began. First the output is "0". After one second, the "0" is replaced by "1", and so on. Here is the code I wrote initially.

#include<stdio.h>
#include<time.h>

void main ()
{
  long int time;

  printf("Hello, let us measure the time!\n");

  time=clock();
    printf("%ld", 0);

  while(time/CLOCKS_PER_SEC<7)
    {
        time=clock();
        if(time%CLOCKS_PER_SEC==0)
        {
            printf("\r");
            printf("%ld", time/CLOCKS_PER_SEC);
        }
    }
}

This gave an output "7" at the end of 7 seconds only.

If I make the following replacements, the code works fine.

    printf("%ld", 0);

by

    printf("%ld\n", 0);

and

            printf("\r");
            printf("%ld", time/CLOCKS_PER_SEC);

by

            printf("\33[A");    //vt100 char, moves cursor up
            printf("\33[2K");   //vt100 char, erases current line
            printf("%ld\n", time/CLOCKS_PER_SEC);

The problem seems that the output wont be sent until the current line is completely determined. What is happening here?

I am using gcc compiler on Ubuntu.

The output stream that you are writing to with printf() will buffer until the newline is received. Since you aren't sending a newline then you get no flush until your application exits or the buffer fills up.

You can flush the output buffer yourself after each printf(), as hyde said in the comment above using fflush(stdout).

Or you can disable buffering by using setbuf( stdout, NULL );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM