在讲进度条前需要了解进度条的原理
\r和\n
\r:将光标移动到本行开头
\n:将光标移到下一行(不同的系统下\n可能代表将光标移动到本行开头并换行)
缓冲区
#include <stdio.h>
int main()
{
printf("hello Makefile\n ");
sleep(3);
return 0;
}
#include <stdio.h>
int main()
{
printf("hello Makefile");
sleep(3);
return 0;
}
运行上面两个代码,第一个代码会将hello Makefile直接输出,不用等3秒
而第二个代码,则过了3秒才将hello Makefile输出,这是因为在执行sleep(3)时hello Makefile\n被保存在缓冲区里,而缓冲区检测到\n这样的符号时会将内容直接输出不用等sleep(3)完。
#include <stdio.h>
int main()
{
printf("hello Makefile\r");
sleep(3);
return 0;
}
#include <stdio.h>
int main()
{
printf("hello Makefile\r");
fflush(stdout);
sleep(3);
return 0;
}
执行上面代码我们发现第一个代码虽然有\r但是并没有输出hello Makefile ,并且被命令提示符覆盖掉,因为\r并没有\n那样会让缓冲区中的数据直接输出。第二个代码后面没有\n也可以直接输出hello Makefile,不用等sleep(3)结束,因为我们在添加了fflush(stdout)。所以我们可以通过fflush(stdout)来让\r拥有\n的效果,以此来实现数据覆盖。
进度条
test.h
#pragma once
#include<stdio.h>
void process();
test.c
#include"proc.h"
#include <string.h>
#include <unistd.h>
#define SIZE 101//字符串的读取以\0结束,所以多出一个位置
#define STYLE '#'
void process()
{
const char *lable="|/-\\";
char bar[SIZE];
memset(bar,'\0',sizeof(bar));//字符串的读取以\0结束
int i=0;
while(i<=100)
{
printf("[%-100s][%d%%][%c]\r",bar,i,lable[i%4]);
fflush(stdout);
bar[i++]=STYLE;
usleep(100000);//10的6次方为1秒,0.1秒
}
printf("\n");
}
main.c
#include"proc.h"
int main()
{
process();
return 0;
}
gcc -o process main.c test.c通过执行此指令将main.c和test.c编译生成process可执行文件。(这里要注意main.c要在test.c的前面不然可能编译不成功)
再通过执行./progess指令执行可执行文件