天天看點

Linux中模拟實作進度條fflush

 一、背景

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).

二、實作

1、Makefile檔案

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、運作結果:

繼續閱讀