martega
martega

Reputation: 2143

Adding a status bar to c++ console applications

I am making a linux application using C++ and it will print info out to the console. Parts of the program will take a while to compute and I would like to add a status bar in the console similar to the one used in wget (I put my own depiction below).

%complete[===========>               ] eta

What would be the best way to accomplish this goal? Are there any useful libraries that make it easy to add this functionality?

Upvotes: 3

Views: 2079

Answers (3)

patraulea
patraulea

Reputation: 11

You can use debconf-apt-progress to run a command while displaying a progress line like apt does. Your command needs to report progress over a pipe fd back to debconf-apt-progress. I haven't figured out how to extract this functionality out of debconf-apt-progress yet.

Upvotes: 0

ibid
ibid

Reputation: 3902

If your program is like wget, that is, it's basically a batch program without the need for a full-screen UI (for which I would recommend ncurses), you can use the trick to print a carriage return (but not line feed) after your line; the next thing you write will overwrite the same line.

Here's a demonstration.

#include <iostream>
#include <unistd.h>

int main(void)
{

        for (int i = 0; i < 10; i++) {
                std::cout << "Status: " << i << "\r" << std::flush;
                sleep(1);
        }
        std::cout << "Completed.\n";
}

Upvotes: 7

The ncurses library should be useful to you. Or you can write the progress line char by char, using backspaces, calling fflush or std::flush, etc.

A simpler way would just to output dots...

Upvotes: 1

Related Questions