23

Many command line tools implement text-based progress bar. Like rpm installing:

installing ##############[45%]

the # grows with the percentage, while keeps itself in a single line. What I want is something similar: I need a progress indicator taking just one line, that is to say, when percentage grows, it got overwritten, instead of make a new line(\n).

I tried this:

   #include <stdio.h>

   int main (){
       int i = 0;
       for (i = 0; i < 10000; i++){
           printf("\rIn progress %d", i/100);
       }
       printf("\n");
   }

\r works to overwrite the single line. However, \r brings cursor to the beginning of line and printf brings cursor to the end, which result in a rapidly waving cursor. You guys can feel it by a little compiling. Can Anyone come up with alternatives to avoid this issue?

oz123
  • 27,559
  • 27
  • 125
  • 187
qweruiop
  • 3,156
  • 6
  • 31
  • 55

5 Answers5

21

This is a problem of the stdout stream being buffered. You have to flush it explicitly (implicit flushing occurs with a \n) using fflush(stdout) after the printf():

fflush(stdout);
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
  • 3
    Thanks! It works fine. Actually I bear little concept of buffered stream, could you present some explanation or further reference in detail? – qweruiop Jan 07 '14 at 02:44
3

Here is how rpm did it, maybe you can write a similar function for your own purpose: printHash.

rpm use \b instead of \r to erase the output line character by character.

cocomac
  • 518
  • 3
  • 9
  • 21
Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
1

I believe using

printf("\e[?25l");

may be able to help. This will hide the cursor. Honestly, I'm not sure if using /r or printf again will override that bit of code and show the cursor, but it's worth a shot. Also, the below code can be used to show the cursor again.

printf("\e[?25h");
ArmaAK
  • 587
  • 6
  • 21
0

To use formatting on your terminal, check the ANSI escape code.

jmlemetayer
  • 4,774
  • 1
  • 32
  • 46
0

Rather than giving your some erroneous and non-portable code lines, I'd recommend you to read through the man pages for your system's termcap and terminfo. It's a bit hard to follow at first, but it's a must-read if your about to start mucking with terminal-dependent code. The Wikipedia pages are a good place to start, but then do give the man pages on your system a read as well.

Also I just realized your question is most definitely a duplicate of a few other questions.

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96
  • Thanks for your info. I'd thank everyone who directs me to some vital subjects that I'm not aware of. – qweruiop Jan 07 '14 at 02:48