赞
踩
\r 回车就是回到这一行开头
\n 换行就是另起一行
代码一:
#include<stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
代码二:
\n
换成了\r
,再次打印会出现什么情况?#include<stdio.h>
int main()
{
printf("hello world\r");
return 0;
}
如下:
sleep:Linux 下的休眠函数,单位是秒
usleep:和sleep 一样,单位ms(即10-6 m)
fflush :刷新缓冲区
代码 3:
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world");
sleep(3);
return 0;
}
fflush
函数来刷新缓冲区代码四:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("hello world");
fflush(stdout);
printf("\n");
sleep(3);
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main()
{
int cnt=10;
while(cnt>=0)
{
printf("%-2d\r",cnt);
fflush(stdout);
sleep(1);
cnt--;
}
printf("\n");
return 0;
}
具备了以上介绍的知识,接下来我们就实现进度条了
processbar:ProcessBar.c main.c
gcc -o $@ $^
.PHONY:clean
clean:
rm -rf processbar
#pragma once #include <string.h> #include <unistd.h> #include <stdio.h> // 进度条箭头 #define TAIL '>' // 进度条的数组大小 #define Length 102 // 进度条加载的进度条 #define Style '=' // 重定义函数指针 typedef void (*callback_t)(double, double); // 进度条的实现 void ProcBar(double total, double current);
#include "ProcessBar.h" #define LIGHT_CYAN "\033[1;36m" // 亮青色 #define NONE "\033[m" //截断 // 显示进度 const char* lable = "|/-\\"; void ProcBar(double total, double current) { char bar[Length]; // 初始化进度条 memset(bar, '\0', sizeof(bar)); int len = strlen(lable); int cnt = 0; double rate = (current * 100.0) / total; // 循环次数 int loop_count = (int)rate; while (cnt < loop_count) { bar[cnt++] = Style; if (rate < 100) bar[loop_count] = TAIL; } // 打印显示 printf(LIGHT_CYAN"[%-100s]"NONE"[%.2lf%%][%c]\r", bar, rate, lable[cnt % len]); // 刷新缓冲区 fflush(stdout); }
#include "ProcessBar.h" // 网络带宽【1mb】 double bandwidth = 1024 * 1024 * 1.0; void download(double filesize, callback_t cb) { // 累计下载的数据量 double current = 0.0; printf("download begin, current: %lf\n", current); while (current <= filesize) { // 使用函数指针更新界面 cb(filesize, current); //从网络中获取数据 //...... // 睡眠 usleep(100000); // 累计下载 current += bandwidth; } printf("\ndownload done, filesize: %lf\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); download(10*1024*1024,ProcBar); // 测试 //ProcBar(100.0, 56.9); //ProcBar(100.0, 1.0); //ProcBar(100.0, 99.9); //ProcBar(100.0, 100); return 0; }
进度条样式 :
进度条百分比:
进度条旋转字符:
进度条颜色:
c语言颜色参考
我们可以根据自己的喜好给进度条上色,在此我们找到颜色参照表
预留进度条大小为 100 个 = ,外加 1 个 > ,加上保存 \0 的位置,定义一个102个单位的长度的bar
数组。
如果将打印放在循环中的话,在打印的时候会变得卡卡的,我们可以将打印放到循环外面,等数组放上=>
后,在一起打印,这样更好
我们又实现了一个函数download()
,把ProcBar()
,作为参数传递给download()
,用usleep函数模拟下载时间,然后循环起来回调processbar()函数,便实现了进度条
最后考虑到第二次下载,bar数组满了,我们再每次调用download()函数时,清空bar数组,完成实现~~
这就实现了我们最终的效果
最后本文就到这里结束了,感谢大家的收看,请多多指点~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。