How to animate the command line?

前端 未结 8 1903
臣服心动
臣服心动 2020-11-27 09:09

I have always wondered how people update a previous line in a command line. a great example of this is when using the wget command in linux. It creates an ASCII loading bar

8条回答
  •  遥遥无期
    2020-11-27 09:56

    There are two ways I know of to do this:

    • Use the backspace escape character ('\b') to erase your line
    • Use the curses package, if your programming language of choice has bindings for it.

    And a Google revealed ANSI Escape Codes, which appear to be a good way. For reference, here is a function in C++ to do this:

    void DrawProgressBar(int len, double percent) {
      cout << "\x1B[2K"; // Erase the entire current line.
      cout << "\x1B[0E"; // Move to the beginning of the current line.
      string progress;
      for (int i = 0; i < len; ++i) {
        if (i < static_cast(len * percent)) {
          progress += "=";
        } else {
          progress += " ";
        }
      }
      cout << "[" << progress << "] " << (static_cast(100 * percent)) << "%";
      flush(cout); // Required.
    }
    

提交回复
热议问题