In C ++, how can a percentage indicator appear at the bottom of a Linux terminal while general printouts are displayed (not overwritten)?

I have a program that iterates over some files, doing different things for them. With each file, the program prints some output to the terminal. This output can take many forms (over which I have no control).

I want to have a percentage progress bar only displayed at the bottom of the terminal output, below all the continuous output of file processing operations. How can i do this?

Please note that I have no access to ncurses.

Using the guide from the previous question , I have a basic attempt at:

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

using namespace std;

void print_progress_bar(int percentage){
  string progress = "[" + string(percentage, '*') + string(100 - percentage, ' ') + "]";
  cout << progress << "\r\033[F\033[F\033[F" << flush;
}

void print_stuff(){
    int number_of_lines = (rand() % 9) + 1;
    for (int i=0; i <= number_of_lines; ++i){
        cout << "some junk output of " << number_of_lines << " lines\n";
    }
}

int main(){
  cout << endl;
  for (int i=0; i <= 100; ++i){
    std::cout << "processing file number " << i << "\n";
    print_stuff();
    print_progress_bar(i);
    usleep(10000);
  }
  cout << endl;
  cout << endl;
  cout << endl;
  cout << endl;
}

      

+3


source to share





All Articles