赞
踩
一、简述
记--简单的控制台下载进度条。
二、效果
Windows:
三、源文件
processBar.c文件
- #include <stdio.h>
- #include <stdlib.h> //rand(), srand()
- #include <time.h>
-
- #define ONEMB (1024*1024)
- #define ONEGB (1024*ONEMB)
-
- //将bute转化为人类容易区分的单位
- int convByteToHumanResult(unsigned int bytes, char* result)
- {
- int i;
- char uint[][5] = {"B", "Kb", "MB", "GB", "TB", "PB"};
- double dbBytes = bytes;
-
- if(NULL == result)
- {
- return -1;
- }
-
- for(i=0; dbBytes>=1024.0;i++)
- {
- dbBytes /= 1024.0;
- }
-
- sprintf(result, "%.2lf%s", dbBytes, uint[i]);
- return i;
- }
-
- //显示进度条
- void showProcessBar(unsigned int total, unsigned int recv, char* info)
- {
- int i;
- float frecv = recv;
- int percent = (int)((frecv/total) * 100);
- char res1[64] = {0};
- char sum1[64] = {0};
- char bar[101] = {0};
-
- for(i=0; i<percent; i++)
- {
- bar[i] = '#';
- }
-
- convByteToHumanResult(recv, res1);
- convByteToHumanResult(total, sum1);
-
- if(NULL != info)
- {
- printf("\r%s total:%s(%u Byte) recv:%s(%u Byte) [%d%%%s] ", info, sum1, total, res1, recv, percent, bar);
- fflush(stdout);
- }
- }
-
- int main(void)
- {
- unsigned int i;
- unsigned int total1 = (unsigned int)188 * ONEMB;
- unsigned int total2 = (unsigned int)1 * ONEGB + 267 * ONEMB;
-
- srand(time(0));//设置随机数种子
-
- printf("Start download aaa.log...\n");
- for(i=0;;)
- {
- showProcessBar(total1, i, "download...");
-
- if(i >= total1)
- {
- break;
- }
-
- i += rand()%1024;
-
- if(i>total1)
- {
- i = total1;
- }
- }
-
- printf("\nDownload aaa.log finish!\n\n");
-
- printf("Start download CProgram.zip...\n");
- for(i=0;;)
- {
- showProcessBar(total2, i, "download...");
-
- if(i >= total2)
- {
- break;
- }
-
- i += rand()%8192;
-
- if(i>total2)
- {
- i = total2;
- }
- }
-
- printf("\nDownload CProgram.zip finish!\n");
-
- return 0;
- }

四、总结
4.1 回到行首使用 '\r' printf("\r");
4.2 擦除一个字符使用退格符'\b',然后用空格覆盖 printf("\b \b");
注:不能擦除换行符,即只能擦除同一行的字符。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。