2

I want to make a more dynamic interface rather than print out a whole new page every time but do not know how to implement it. For example, if we have a download bar that goes from 0% to 100%, I want to change the number directly on the terminal instead of printing out 100 lines with 1%, 2%, 3%. What should I do with it?

2
  • The simplest solution is to output a carriage return \r to flip the cursor position to the start of the line and then overwrite the previous output line with the new line with the new percentage. The main alternatives involve things like ncurses. You could try backspacing too. Apr 17, 2013 at 17:14
  • If you do this, provide an option to disable it. If I redirect your program's output to a file, I'd rather not have a bunch of control characters in it. Apr 17, 2013 at 17:14

3 Answers 3

0

The simpler choice, if you want to keep it on a single line, would be to use \r. Printing \r will move your cursor to the beginning of the line, giving you the ability to print hover the old characters.

A solution would look something like

for (i = 0; i < 100; ++i)
{
    printf("\r%3i%%", i);
    fflush(stdout);
    /* ... */
}

If you need more advanced control over the terminal, you can use termcaps.

1
  • %3i prints the number with enought spaces to make the output always use 3 characters. %% prints a percent sign after it. See printf manpage
    – tomahh
    Apr 17, 2013 at 17:21
0

You could print a \r character, which is called the 'carriage-return' and should in most cases return the cursor to the beginning of the line so you can print over the text that's already there. I say should because it's not guaranteed and it depends on the shell the program is running in. If you want to do more exotic stuff you should look into ncurses.

0

You should use a cross-platform terminal access library, such as libncurses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.