1.缓冲区的理解
缓冲区是一块临时的内存区域,用来在数据从源(如程序)移动到目的地(如屏幕、文件)时,暂存这些数据。
2.为什么使用缓冲区
频繁的、小量的I/O操作(比如每次printf都直接写屏幕)效率非常低。系统调用(如write)的开销很大。缓冲区将多次小的输出收集起来,然后一次性进行大批量写入,极大地提高了效率。
标准I/O库为不同的流(如标准输出stdout)设置了不同的缓冲策略,常见的有:
全缓冲:缓冲区满了才刷新(通常用于文件)。
行缓冲:遇到换行符\n时刷新缓冲区(通常用于终端stdout)。
无缓冲:数据立即输出,不经过缓冲区(通常用于标准错误stderr,确保错误信息能及时看到)。
我们将数据写入文件的过程,其实的是我们将数据写入内核缓冲区,至于数据什么时候写入文件由操作系统决定。
3.进度条的原理
倒计时原理,使用行缓存'\n' 会从用户缓冲区刷新数据到终端或者内核缓冲区,由于倒计时不需要换行,我们可以使用'\r' 和flush代替,'\r'回车,flush刷新数据到终端。
#include<iostream> #include<unistd.h> #include<c++/12/iomanip> #include<vector> using namespace std; void percentage_bar() { int i=10; while(i--) { cout<<setw(2)<<i<<'\r'<<flush; // setw(2) 使打印的i占2个位置 usleep(500000); } } // 实现10秒倒计时目标进度条: [---------->][20%] [------------------------->][50%] [-------------------------------------------------->][100%] #include<iostream> #include<unistd.h> #include<c++/12/iomanip> #include<string> using namespace std; void percentage_bar() { int i=0; string str(101,'\0'); str[i]='-'; while(i<=100) { cout<<'['<<setw(100)<<str<<'>'<<']'<<'['<<setw(3)<<i<<'%'<<']'<<'\r'<<flush; i++; str[i]='-'; usleep(200000); } cout<<endl; }