在命令列介面(CLI)程式中,長時間執行的任務(如檔案複製、資料處理、下載)需要視覺化進度回饋。一個簡單的文字模式進度條能大幅提升使用者體驗。
\r 與退格符 \b\r (Carriage Return):將游標移至當行行首,不換行。\b (Backspace):將游標左移一格,可配合覆寫實現動畫效果。fflush(stdout):強制刷新輸出緩衝區,確保立即顯示。#include <stdio.h>
#include <unistd.h> // for sleep()
void displayProgress(int progress) {
// 1. 用退格符清空當前行(假設進度條固定寬度 106 字元)
for (int k = 0; k < 106; k++) {
putchar('\b');
}
// 2. 繪製已完成部分(用 '+' 表示)
for (int j = 0; j < progress; j++) {
putchar('+');
}
// 3. 繪製未完成部分(用 '-' 表示)
for (int j = 0; j < 100 - progress; j++) {
putchar('-');
}
// 4. 顯示百分比數字,%3d 確保寬度固定為 3 字元(含前導空格)
fprintf(stdout, " %3d%%", progress);
// 5. 關鍵:刷新緩衝區,否則輸出可能延遲顯示
fflush(stdout);
}
int main() {
for (int i = 0; i <= 100; i++) {
displayProgress(i);
usleep(50000); // 模擬任務耗時,Linux/macOS 用 usleep,Windows 用 Sleep(50)
}
putchar('\n'); // 結束換行
return 0;
}
%3d%% 確保百分比數字始終佔 3 字元(如 5%, 50%, 100%),避免數字位數變化導致進度條抖動。
// Linux / macOS
#include <unistd.h>
usleep(50000); // 微秒
// Windows
#include <windows.h>
Sleep(50); // 毫秒
\r現代終端機支援 \r 直接回行首,代碼可簡化為:
void displayProgressV2(int progress) {
printf("\r["); // 回行首
for (int i = 0; i < progress; i++) putchar('=');
for (int i = 0; i < 100 - progress; i++) putchar(' ');
printf("] %3d%%", progress);
fflush(stdout);
}
\033[32m 綠色)美化輸出。ioctl 或 GetConsoleScreenBufferInfo 取得終端機寬度自適應。| / - \ 旋轉動畫。fflush(stdout) → 輸出被緩衝,進度條卡住不動。isatty(fileno(stdout)) 判斷是否為終端機。SetConsoleMode 啟用虛擬終端機序列。