江西建设厅网站查询施工员,祥云平台做的网站效果好,江苏自助建站平台,h5设计制作文章目录 铺垫回车换行缓冲区概述强制冲刷缓冲区 简单实现倒计时功能进度条小程序版本一实例代码效果展示分析 版本二 铺垫
回车换行
回车和换行是两个独立的动作
回车是将光标移动到当前行的最开始#xff08;最左侧#xff09;
换行是竖直向下平移一行
在C语言中… 文章目录 铺垫回车换行缓冲区概述强制冲刷缓冲区 简单实现倒计时功能进度条小程序版本一实例代码效果展示分析 版本二 铺垫
回车换行
回车和换行是两个独立的动作
回车是将光标移动到当前行的最开始最左侧
换行是竖直向下平移一行
在C语言中\n是同时进行了回车换行\r实现了回车操作
缓冲区
概述
先来看一个小现象
实例代码
#includestdio.h
#includeunistd.h
int main()
{printf(hello gwj,hello Linux...\n);sleep(3);return 0;
} 运行mytest.exe执行程序会输出hello gwj,hello Linux...紧接着调用sleep函数休眠三秒
如果将printf函数中\n删掉会出现什么结果呢 现象先休眠三秒在最后结束的狮虎打印出内容 这这种场景中sleep函数和printf函数哪一个先运行的呢 答案是printf先运行在休眠的这三秒时间里printf已经执行完了字符串被保存在缓冲区
缓冲区的概念需要在操作系统层面上理解单纯在语言基础上是很难理解的
缓冲区是一个内存空间当休眠的时候字符串在缓冲区里当程序结束return 0时强制冲刷缓冲区再打印出字符串。
强制冲刷缓冲区
任何一个C语言程序都会默认打开三个流
stdin标准输入流stdout标准输出流stderr比爱准错错误
可以通过fflush函数来刷新缓冲区 示例代码 #includestdio.h#includeunistd.hint main(){printf(hello gwj,hello Linux...);fflush(stdout); sleep(3);return 0;} 现象 简单实现倒计时功能
示例代码 1 #includestdio.h2 #includeunistd.h3 int main()4 {5 int cnt9;6 while(cnt0)7 {8 printf(%d\r,cnt);9 fflush(stdout); 10 cnt--;11 sleep(1);12 }13 return 0;14 }
效果展示 代码解读 倒计时使用新数字去覆盖老数字并且都出一同一位置因此在printf函数里不能使用\n使用换行会让新数字在老数字下面。
正确做法是在printf函数后面使用\r回车符号每打印一个数字让光标回到这一行最开始的位置这样打印出来的新数字就会覆盖旧数字。
但是\r不会冲刷缓冲区因此每打印完一个数字调用 fflush(stdout)来冲刷缓冲区。
进度条小程序
版本一
实例代码
Processbar.h文件
#pragma once #includestdio.hvoid ProcBar(); #includeProcessbar.h
#includestring.h
#includeunistd.h #define Length 101
#define Style # const char *lable|/-\\; //version1:
void ProcBar()
{ char bar[Length]; memset(bar,\0,sizeof(bar)); int lenstrlen(lable); int cnt0; while(cnt100) { printf([%-100s][%3d%%][%c]\r,bar,cnt,lable[cnt%len]); fflush(stdout); bar[cnt]Style; cnt; usleep(20000); } printf(\n);
} 效果展示 分析
该进度条的原理是一次比一次多打印一点内容、
定义一个bar数组通过循环每次多打印一个字符视觉上就会形成进度条是从右向左走
由于进度条每次打印是在同一行上因此需要\r符号让光标回到最开始的位置
版本二
Processbar.h文件
#pragma once #include stdio.h typedef void(*callback_t)(double, double); void ProcBar(double total, double current);
Main.c文件
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); return 0;
}
Processbar.c文件
#includeProcessbar.h
#includestring.h
#includeunistd.h #define Length 101
#define Style # //version 2
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; usleep(20000); } printf([%-100s][%.1lf%%][%c]\r, bar, rate, lable[cnt%len]); fflush(stdout);
} 效果展示