Linux-进度条的实现

首先创建源代码文件和头文件, 然后创建makefile文件构建自动化编译工具。

  

makefile文件

  1 processbar: main.c processBar.c
  2     gcc -o $@ $^
  3 
  4 .PHONY:clean
  5 clean:
  6     rm -rf processbar     

 然后实现进度条的编写

main.c

//进度条
 26 #include<unistd.h>
 27 
 28 //函数指针类型
 29 typedef void (*callblack_t) (int);
 30 
 31 //开始下载过程
 32 void Download(callblack_t cal)
 33 {
 34     //数据总量
 35     int i_total = 1000;
 36     //当前下载量
 37     int i_curr = 0;
 38     //下载百分比
 39     int i_rate = 0;
 40 
 41     //开始下载
 42     while(i_curr <= i_total)
 43     {
 44         //使程序在此休眠 usleep是以微秒为单位的
 45         usleep(50000);                                                                                                                                              
 46 
 47         //计算当前下载百分比
 48         i_rate = ((i_curr * 100)/ i_total);
 49         //回调打印进度条函数
 50         cal(i_rate);
 51 
 52         //每次的下载量
 53         i_curr += 10;
 54 
 55     }
 56 
 57     printf("\n");
 58 
 59 }int main(void)
 63 {
 64     Download(processbar);
 65    
 66     return 0;
 67 }



processBar.h

#pragma once  
  2 
  3 #include <stdio.h>
  4 
  5 #define SIZE 102
  6 #define PB1 '='
  7 #define PB2 '>'
  8 
  9 extern void processbar(int);                                                                                                                                        
~

processBar.c

char bar[SIZE] = { 0 };
 38 const char* sroll = "|\\-/";
 39 
 40 void processbar(int i_rate)
 41 {
 42     if(i_rate < 0 && i_rate > 100) return;                                                                                                                          
 43 
 44     int i_len = strlen(sroll);
 45     printf("[%-100s][%d%%][%c]\r", bar, i_rate, *(sroll + (i_rate % i_len)));
 46     fflush(stdout);
 47 
 48     bar[i_rate++] = PB1;
 49     if(i_rate < 100)
 50     {
 51         bar[i_rate] = PB2;
 52     }
 53 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值