10

In Linux, While stdout to command line, I want to update specific area, such as the apt-get output:

54% [Waiting for headers] [Waiting for headers]        211 kB/s 3s

the percentage, kB/s and second will update each second.

If we use printf then we will get multiple lines output them. I have tried following printf:

printf("\e[1;1H\e[2J");

But it cleans all the output.

My question is how to update specific area and keep others stable?

coanor
  • 3,746
  • 4
  • 50
  • 67

2 Answers2

9

Use the carriage return. It will move the cursor back to the start of the line, from which you can overwrite what was in the line before. For example:

printf("Hello, world!\rX");

Will be visible as:

Xello, world!

Make sure you flush stdout often if you want it to be visible:

fflush(stdout);
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • You may want to add `\027[k` after `\r` to clear the line. This assumes ANSI terminal escape sequences, which most terminals support. – lhf May 28 '13 at 02:53
3

In addition (of the useful \r & fflush advice above), if you want a full screen console output, consider using ncurses. If you want an editable input line, the GNU readline library is useful too!

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547