文章

C 终端进度条模拟

Windows

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <stdio.h>
#include <windows.h>
#include <time.h>

void process() {
    srand(time(NULL));

    char style[5] = {'+', '-', '*', '>', '/'};
    char loading[120] = {};
    char out[150] = {};

    int cnt = 0;

    while (cnt <= 100) {
        // 格式1: [>>>>>  ]
        loading[cnt] = style[3];

        // memcpy(loading+cnt, &style[4], sizeof(style[4]));

        // 格式2:[===>   ]
        // loading[cnt] = '=';
        // loading[cnt+1] = style[3];

        sprintf(out, "[%-102s] [%d%%] [%c]", loading, cnt, style[cnt%5]);

        printf("%s\r", out);
        fflush(stdout);
        cnt++;

        Sleep(rand() % 201 + 10);
    }

    printf("\n");
}

int main() {
    process();
    return 0;
}

Linux

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

void process() {
    srand(time(NULL));

    char style[5] = {'+', '-', '*', '>', '/'};
    char loading[120] = {};
    char out[150] = {};

    int cnt = 0;

    while (cnt <= 100) {
        // 格式1: [>>>>>  ]
        // loading[cnt] = style[3];

        // memcpy(loading+cnt, &style[4], sizeof(style[4]));

        // 格式2:[===>   ]
        loading[cnt] = '=';
        loading[cnt+1] = style[3];

        sprintf(out, "[%-102s] [%d%%] [%c]", loading, cnt, style[cnt%5]);

        printf("%s\r", out);
        fflush(stdout);
        cnt++;

        usleep(rand() % 201000 + 10000);
    }

    printf("\n");
}

int main() {
    process();
    return 0;
}
本文由作者按照 CC BY 4.0 进行授权