1.文件緩沖區(qū)
1.1介紹
為緩和 CPU 與 I/O 設備之間速度不匹配,文件緩沖區(qū)用以暫時存放讀寫期間的文件數(shù)據(jù)而在內存區(qū)預留的一定空間。使用文件緩沖區(qū)可減少讀取硬盤的次數(shù)。
1.2緩沖文件系統(tǒng)
系統(tǒng)自動地在內存為程序中每一個正在使用的文件開辟一塊文件緩沖區(qū)。
- 從內存向磁盤輸出數(shù)據(jù),先送到內存中的緩沖區(qū),緩沖區(qū)裝滿后一起輸送到磁盤上。
- 從磁盤向計算機讀入數(shù)據(jù),從磁盤文件中讀取數(shù)據(jù)輸入到內存緩沖區(qū)(充滿緩沖區(qū)),從緩沖區(qū)逐個地將數(shù)據(jù)送到程序數(shù)據(jù)區(qū)(程序變量等)。
- 緩沖區(qū)的大小根據(jù)C編譯系統(tǒng)決定。
1.3沖刷函數(shù)fflush
int fflush( FILE *stream );
將緩沖區(qū)內數(shù)據(jù)寫到stream 指定文件。
成功返回 0
錯誤返回 EOF
高版本vs無法使用
fclose關閉文件時也會刷新緩沖區(qū)
#include <stdio.h>
#include <windows.h>
int main()
{
FILE* pf = fopen("test7.txt", "w");
if (!pf)
{
perror(fopen);
return 1;
}
fputs("abcdef", pf); //數(shù)據(jù)輸出到buffer
//此時文件中無內容
Sleep(10000); //睡眠10s
fflush(pf); //刷新緩沖區(qū)
Sleep(10000); //睡眠10s
//此時數(shù)據(jù)到達文件
fclose(pf);
pf = NULL;
return 0;
}
1.4認識linux下的緩沖區(qū)
在linux下gcc編譯這兩段代碼時 結果是不同的 左邊先輸出后睡眠 右邊先睡眠后輸出
c語言不是從上到下一行一行執(zhí)行的嗎?
確實是的 實際上printf先于sleep執(zhí)行但是sleep執(zhí)行完后這個程序才結束 才會輸出信息
為什么執(zhí)行流到printf時 不直接顯示以及為什么左邊加了換行就能先顯示?
c語言存在輸出緩沖區(qū)(一段內存空間) 顯示器設備一般的刷新策略是行刷新 即碰到\n就把\n之前的所有的字符顯示出來 所以左邊代碼先顯示 后邊代碼存入到緩沖區(qū) 直到程序結束才顯示
當一個程序執(zhí)行會自動打開stdin srdout stderr三個標準IO流
如何在沒有換行符的情況下讓他執(zhí)行到printf時就顯示?
#include <stdio.h>
#include<unistd.h>
int main()
{
printf("hello linux!");
fflush(stdout);
sleep(3);
return 0
}
2.linux小程序的實現(xiàn)
2.1 回車\r和換行\(zhòng)n
老式鍵盤的
Enter
: 實際上是 換行+回車[C語言中的\n也是]
#include <stdio.h>
#include<unistd.h>
int main()
{
int count = 5;
while(count)
{
printf("count是: %d\n",count);
count--;
sleep(1);
return 0;
}
}
可以正常輸出
#include <stdio.h>
#include<unistd.h>
int main()
{
int count = 5;
while(count)
{
printf("count是: %d\r",count);
count--;
sleep(1);
return 0;
}
}
不輸出任何內容
2.2倒計時程序
#include <stdio.h>
#include<unistd.h>
int main()
{
int count = 5;
while(count)
{
printf("count是: %d\r",count);
fflush(stdout);
count--;
sleep(1);
return 0;
}
}
每執(zhí)行一次printf 將要輸出的信息輸出到緩沖區(qū) 當執(zhí)行fflush函數(shù)時 將信息從緩沖區(qū)刷到顯示器 之后\r回車 光標回到行首 count–
2.3進度條小程序
sleep/usleep
代碼
文章來源:http://www.zghlxwxcb.cn/news/detail-766882.html
運行結果
linu-vim-c-bar文章來源地址http://www.zghlxwxcb.cn/news/detail-766882.html
到了這里,關于linuxC語言緩沖區(qū)及小程序的實現(xiàn)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!