How should I add a stationary progress bar to a C++ program that produces terminal output (in Linux)? -
i have existing program contains loop on files. various things, providing lots of terminal output. want have overall progress bar remains stationary on same line @ bottom of terminal while of output file operations printed above it. how should try this?
edit: so, clear, i'm trying address display problems inherent in bit following:
#include <unistd.h> #include <iostream> #include <string> using namespace std; int main(){ (int = 0; <= 100; ++i){ std::cout << "processing file number " << << "\n"; string progress = "[" + string(i, '*') + string(100-i, ' ') + "]"; cout << "\r" << progress << flush; usleep(10000); } }
the portable way of moving cursor around know of using \r
move beginning of line. mention output stuff above progress. fortunately, in luck since you're on linux , can use terminal escape codes move around terminal freely. @ example:
#include <unistd.h> #include <iostream> #include <string> using namespace std; int main() { cout << endl; (int i=0; <= 100; ++i) { string progress = "[" + string(i, '*') + string(100-i, ' ') + "]"; cout << "\r\033[f" << << "\n" << progress << flush; usleep(10000); } }
here, added ability print progress value above progress bar moving beginning of line using \r
, 1 line using escape code \033[f
before printing. then, printed 1 line, moved down 1 line \n
, re-printed progress.
you can go further , move cursor x,y position in terminal before printing. use escape code \033[y;xf
before output.
for list of escape codes, check out wikipedia: https://en.wikipedia.org/wiki/ansi_escape_code#csi_codes
so, possible achive behavior without using additional libs ncurses
, maybe want if intend create more gui-like experience.
fixing attempt:
void print_progress_bar(int percentage){ string progress = "[" + string(percentage, '*') + string(100 - percentage, ' ') + "]"; cout << progress << "\r\033[f\033[f\033[f" << flush; } int main(){ cout << endl; (int i=0; <= 100; ++i){ std::cout << "processing file number " << << "\n"; std::cout << " doing thing file number " << << "\n"; std::cout << " doing thing file number " << << "\n"; print_progress_bar(i); usleep(10000); } cout << endl; cout << endl; cout << endl; cout << endl; }
Comments
Post a Comment