C语言 进度条

                                                              C语言 进度条

一、简述

      记--简单的控制台下载进度条。

二、效果

       Windows:        

       Linux:

三、源文件

       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");

              注:不能擦除换行符,即只能擦除同一行的字符。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值