Home > Net >  Print neat progress bar from macOS terminal command prompt
Print neat progress bar from macOS terminal command prompt

Time:08-01

macOS terminal is of type xterm-256color. I'd like to print colored progress bar with special characters.

for example, I uses printf with the symbol \xb0 to present the progress bar :

printf("%s", msg.c_str());

in debugger : 
(lldb) p msg
(const std::string) $0 = "[\xb0\xb0\xb0\xb0]"

But apparently, it prints invisible symbols. Any idea how to print \xb0 in terminal ?

Furthermore, is there any way print messages that overrun the current line? I wish to show the progress bar advancing, and not printing it in multiple lines that each represent different percentage state.

Thanks !

CodePudding user response:

Well doing it from scratch is pretty cumbersome.

Why don't you use an existing library like this, the code seems pretty straightforward.

You get all fancy progress bars, with color, and it seems pretty intuitive, and its very customizable.

(From the Github Repo, here)

#include <indicators/progress_bar.hpp>
#include <thread>
#include <chrono>

int main() {
  using namespace indicators;

  ProgressBar bar{
    option::BarWidth{50},
    option::Start{"["},
    option::Fill{"="},
    option::Lead{">"},
    option::Remainder{" "},
    option::End{"]"},
    option::PostfixText{"Extracting Archive"},
    option::ForegroundColor{Color::green},
    option::FontStyles{std::vector<FontStyle>{FontStyle::bold}}
  };
  
  // Update bar state
  while (true) {
    bar.tick();
    if (bar.is_completed())
      break;
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }

  return 0;
}

I can change the total length of the bar by changing the value of option::BarWidth, or make the fill to 0 by changing option::Fill{"="} to option::Fill{"0"}

  • Related