C实现进度条

#include <stdio.h>

int main() {
    int pwidth = 75;
    int i, j;
    for (i = 0; i < pwidth; i++) {
        // 构建进度条
        printf("%3d%% [", i * 100 / pwidth);
        for (j = 0; j <= i; j++)
            putchar('=');
        for (; j < pwidth; j++)
            putchar(' ');
        putchar(']');
        fflush(stdout);
        sleep(1);
        // 把刚才输出的都擦掉,用\r会有问题。
        for (j = 0; j < pwidth + 7; j++)
            putchar('\b');
    }
    putchar('\n');
    return 0;
}

02-19,补充:


Terminal Control Escape Sequences 找到

Erase End of Line <ESC>[K

  • Erases from the current cursor position to the end of the current line.

Erase Start of Line <ESC>[1K

  • Erases from the current cursor position to the start of the current line.

Erase Line <ESC>[2K

  • Erases the entire current line.

Erase Down <ESC>[J

  • Erases the screen from the current line down to the bottom of the screen.

Erase Up <ESC>[1J

  • Erases the screen from the current line up to the top of the screen.

Erase Screen <ESC>[2J

  • Erases the screen with the background colour and moves the cursor to _home_.

若是tty的话,可以这样:

printf("\r\x1b[K%3d%% [", i * 100 / pwidth);

标签: none

添加新评论