(1)先引入一个概念:行缓冲区
\r
和\n
\r
表示回车
\n
表示回车并换行
①代码一
-
#include<stdio.h>
-
#include<unistd.h>
-
int main()
-
{
-
printf("hello Makefile!\n");
-
sleep(3);
-
return 0;
-
}
打印出了hello Makefile!,然后三秒后结束了运行
②代码二
-
#include<stdio.h>
-
#include<unistd.h>
-
int main()
-
{
-
printf("hello Makefile!");
-
sleep(3);
-
return 0;
-
}
什么也没显示,程序结束后打印出了hello Makefile!,同时在同一行出现了命令提示符
③代码三
-
#include<stdio.h>
-
#include<unistd.h>
-
int main()
-
{
-
printf("hello Makefile!");
-
fflush(stdout);
-
sleep(3);
-
return 0;
-
}
打印出了hello Makefile!,然后三秒后结束了运行,同时在同一行出现了命令提示符
这是因为 printf("hello Makefile!"); 没有包含换行符,缓冲区的内容不会立即被刷新
printf 会先将数据写入到一个缓冲区中,只有在遇到换行符(\n),缓冲区满了,或者程序正常结束时,缓冲区的内容才会被真正输出到终端。
(2)进度条项目
根据上述特性,可以写出进度条,用字符#
表示进度,打印出以后进行回车不换行,每次多加一个#
,就能够实现进度条在加载的效果,而每次变更打印的内容为数字的话,就可以有进度在变更的效果。
<Processbar.h>
-
#pragma once
-
#include<stdio.h>
-
typedef void(*callback_t)(double,double);
-
void ProcBar(double total,double current);
<Processbar.c>
-
#include"Processbar.h"
-
#include<string.h>
-
#include<unistd.h>
-
#define length 101
-
#define Style '#'
-
// version 1
-
const char *lable = "|/-\\";
-
//void ProcBar()
-
//{
-
// char bar[length];
-
// memset(bar,'\0',sizeof(bar));
-
//
-
// int len = strlen(lable);
-
// int cnt = 0;
-
// while(cnt <= 100)
-
// {
-
// printf("[%-100s][%3d%%][%c]\r",bar,cnt,lable[cnt%len]);
-
// fflush(stdout);
-
// bar[cnt++] = Style;
-
// usleep(60000);
-
// }
-
// printf("\n");
-
//
-
//}
-
//
-
// version 2
-
void ProcBar(double total,double current)
-
{
-
char bar[length];
-
memset(bar,'\0',sizeof(bar));
-
int len = strlen(lable);
-
double rate = (current*100.0)/total;
-
int cnt = 0;
-
int loop_count = (int)rate;
-
while(cnt <= loop_count)
-
{
-
bar[cnt++] = Style;
-
//usleep(10000);
-
}
-
printf("[%-100s][%.1lf%%][%c]\r",bar,rate,lable[cnt%len]);
-
fflush(stdout);
-
}
<Main.c>
-
#include"Processbar.h"
-
#include<stdio.h>
-
#include<unistd.h>
-
//download
-
void download(double filesize,callback_t cb)
-
{
-
double current = 0.0;//已下载量
-
double bandwidth = 1024*1024*1.0;//带宽
-
printf("download begin, current:%lf\n",current);
-
while(current<=filesize)
-
{
-
cb(filesize,current);
-
//从网络中获取数据
-
current+=bandwidth;
-
usleep(100000);
-
}
-
printf("\ndownload done, filesize:%.3lf\n",filesize);
-
}
-
int main()
-
{
-
download(100*1024*1024,ProcBar);
-
download(2*1024*1024,ProcBar);
-
download(200*1024*1024,ProcBar);
-
download(400*1024*1024,ProcBar);
-
download(50*1024*1024,ProcBar);
-
//ForTest();
-
// ProcBar(100.0,56.9);
-
// ProcBar(100.0,1.0);
-
// ProcBar(100.0,99.9);
-
// ProcBar(100.0,100);
-
// return 0;
-
}