Linux中模拟实现进度条

 一、背景

1、进度条实现原理

   进度条的实现必须了解以下几个知识点,回车换行、缓冲区

   换行:换行就是光标只从上一行行尾移至下一行行尾

   回车:回车就是光标从行尾移至行首

   回车换行:回车换行就是光标从行尾移至下一行行首

   缓冲区:指由多个以不同速度或优先级运行的硬件或程序进程共享的数据存储区,在其中暂时保存数据。缓冲区使进程之间的相互等待变少了。先结束的进程可以把结果放入缓冲区内,进行下面的工作,而后做完的进程可以从缓冲区内取出原来的数据继续工作。缓冲区的作用是:在高速和低速设备之间起一个速度平滑作用;暂时存储数据;经常访问的数据可以放进缓冲区,减少对慢速设备的访问以提高系统的效率。

 

2、fflush函数

   作用:刷新缓冲区

fflush

int fflush ( FILE * stream );

Flush stream

If the given stream was open for writing and the last i/o operation was an output operation, any unwritten data in the output buffer is written to the file.
If it was open for reading and the last operation was an input operation, the behavior depends on the specific library implementation. In some implementations this causes the input buffer to be cleared, but this is not standard behavior.
If the argument is a null pointer, all open files are flushed.
The stream remains open after this call.
When a file is closed, either because of a call to fclose or because the program terminates, all the buffers associated with it are automatically flushed.

Parameters

stream

Pointer to a FILE object that specifies a buffered stream.

 

Return Value

A zero value indicates success.
If an error occurs, EOF is returned and the error indicator is set (see feof).

 

二、实现

 

1Makefile文件

 

2、源代码

    #include<stdio.h>

#include<unistd.h>

#include<string.h>

int main()

{

int i=0;

char bar[102];

bar[0]='\0';

char lable[6]="-\\|/";

while(i<=100)

{

           printf("[%-101s][%d%%][%c]\r",bar,i,lable[i%4]);

   fflush(stdout);

   usleep(100000);

   bar[i++]='#';

   bar[i]='\0';

}

printf("\n");

   return 0;

}

 

3、运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值