公司动态

【Linux系统编程】第一个程序:进度条实现

📅 2026/7/24 18:03:58
【Linux系统编程】第一个程序:进度条实现
目录1. 行缓冲区2.进度条的实现main.cprocess.hprocess.c实现基础vim的熟练使用了解并会使用Mmakefilegcc相关知识。补充知识回车换行这两不是一回事1.回车\r回到当前行的起始位置。2.换行\n就是换到下一行。1. 行缓冲区观察下面程序运行现象#include stdio.h int main() { printf(hello bite!\n); sleep(3); return 0; }通过运行程序我们会发现printf函数的调用是在sleep“之后”的但实际上并不是C/C执行程序的逻辑始终是从上往下的printf没有及时打印出来的原因是因为该内容暂时存放在了缓冲区使用fflush可以立即刷新缓冲区在Linux下sleep的使用需要包含unistd.h。#include stdio.h int main() { printf(hello bite!); fflush(stdout); sleep(3); return 0; }2.进度条的实现实现逻辑1.makefile的准备2.touch main.c、process.c、process.h3.进度条的逻辑链比率的计算填充进度字符刷新进度条进度条完成换行main.c1 #include process.h 2 #includeunistd.h 3 #includestdlib.h 4 #includetime.h 5 6 7 double gtotal 1024.0; //目标文件大小 8 double gspeed 1.0; //网络速度-优化为动态 9 10 //回调函数 11 void DownLoad(double total,flush_t cb) 12 { 13 double level[] {0.01,40.0,35.7,22.8,0.05,0.9,57.5,2.4,5.7}; 14 int num sizeof(level)/sizeof(level[0]); 15 16 double current 0.0; 17 while(1) 18 { 19 usleep(100000); 20 double speed level[rand()%num]; 21 current speed; 22 if(current total) 23 { 24 current total; 25 cb(total,current,speed,MB/s);//更新进度条 26 break; 27 } 28 else{ 29 cb(total,current,speed,Mb/s); 30 } 31 } 32 } 35 int main() 36 { 37 srand(time(NULL)); 38 DownLoad(gtotal,Process); 39 printf(DownLoad:\n); 40 return 0; 41 }process.h1 #includestdio.h 2 typedef void(*flush_t)(double total,double current,double speed,const char*userinfo); 3 void Process(double total,double current,double speed,const char*userinfo);process.c1 #includeprocess.h 2 #includestring.h 3 #includeunistd.h 4 5 #define SIZE 102 6 #define LABEL 7 8 void Process(double total,double current,double speed,const char* userinfo) 9 { 10 if(current total) 11 { 12 return; 13 } 14 15 static const char* label[] {load.,load..,load...}; 16 static int index 0; 17 int size sizeof(label)/sizeof(label[0]); 18 //1.计算比率 19 double rate current*100/total; 20 char out_bar[SIZE]; 21 memset(out_bar,\0,sizeof(out_bar)); 22 //2.填充进度字符 23 int i 0; 24 for(;i (int)rate;i) 25 { 26 out_bar[i] LABEL; 27 } 28 //3.刷新缓冲区 29 printf([%-100s][%5.1lf%%][%-7s] | %.1lf/%.1lf,speed:%.1lf%s\r,\ 30 out_bar,rate,label[index],current,total,speed,userinfo); 31 fflush(stdout); 32 index; 33 index % size; 34 35 //4.进度条完成,换行 36 if(current total) 37 { 38 printf(\r\n); 39 } 40 }几个小细节1.C中默认是右对齐输出时前面的内容会被覆盖掉所以需要加 - 表示为左对齐。2.为了使输出内容长度不那么“跳动”可以提前预留空间如%5s,就是预留5个空间可以和 - 结合使用%-5s就是在字符串输出的时预留5格空间且多的空格在前面也就是左对齐。完~