這是一個快速入侵,顯示使用ANSI轉義產生wget
類似行爲的進度條。可以進行額外的約束檢查調整,但這僅僅是一個簡單的例子。在終端寬度爲sz
(目前限制爲70個字符)的情況下,重複調用progress
會產生一個進度條,其中總計t
中的當前值爲n
。完成對progress_clear
的呼叫後,將清除線上剩餘的任何字符。 (也可以只打印newline
離開竣工米就行了)
雖然逃逸代碼的可用性是終端相關的,在選擇時,\033[s
(保存光標位置)和\033[u
(恢復保存位置 )在支持逃生的終端之間相當普遍。
有許多方法來處理從printf
fieldwidths
或padding
格式來memcpy
填補字符數組。這只是示出了具有逸出的線路控制輸出,以提供測量儀的主體:
#include <stdio.h>
#include <unistd.h> /* for usleep */
#define MAXPM 120
/* progress meter called with current increment 'n' of a
total number of increments 't' fit into a maximum terminal
width of 'sz'. (< MAXPM) It should be called and updated
without intervening output to stdout.
*/
static inline void progress (int n, int t, int sz)
{
int pct = (n * 100)/t;
char mkr[] = { [0 ... MAXPM] = '=', [MAXPM+1] = 0 };
char spc[] = { [0 ... MAXPM] = ' ', [MAXPM+1] = 0 };
int nmkr = (pct * sz)/100;
int nspc = sz - nmkr;
mkr[nmkr] = 0; /* terminate at appropriate size */
spc[nspc] = 0;
printf ("\033[s\033[u %3d %% [%s%s]\033[u", pct, mkr, spc);
fflush (stdout); /* required due to no newline */
}
/* simple clear to end of line - if desired, otherwise, just print newline */
void progress_clear()
{ printf ("\033[K"); fflush (stdout); }
int main() {
int i = 0;
for (i = 0; i <= 50; i++) {
/* do something that returns progress */
progress (i, 50, 70);
usleep (100000);
}
// progress_clear(); /* clean up - remove meter (if wanted) */
printf ("\n");
return 0;
}
實施例(具有newline
增補):
$ ./bin/progbar
0 % [ ]
2 % [= ]
4 % [== ]
6 % [==== ]
(snip)
94 % [================================================================= ]
96 % [=================================================================== ]
98 % [==================================================================== ]
100 % [======================================================================]
Forogt感謝您任何暗示和或骷髏 – Robert 2014-12-06 16:25:21
你可能會覺得ncurses庫很有趣。 – 2014-12-06 16:26:36
對不起dandan78,我覺得你的編輯沒有什麼幫助,需要Linux中的ANSI C規範,否則誰讀,他怎麼能理解我們正在談論的終端?誰知道C可能對閱讀這篇文章感興趣?此編輯可能會導致愚蠢的回覆。 – Robert 2014-12-06 16:28:16