前序:
首先先理解一下什么是回車與換行;回車和換行是兩個概念,它們不是一個東西;
- 回車:光標回到開始;
- 換行:換到下一行;
如下圖:
行緩沖區
如何理解緩沖區問題?
可以認為,緩沖區就是一塊內存塊,有的輸出的內容會先這個緩沖區中,在緩沖區刷新時一起輸出到輸出端;如下圖
如果想讓他立馬刷新打印怎么辦?
printf 的底層就是stdout,也就是fprintf(stdout,"hello world"),所以直接刷新stdout就好了;
?只回車,不刷新?簡單倒計時
實踐--倒計時程序
version-1?
process.h
#pragma once #include<stdio.h>void FFlushProcess(double current, double total); void process_v1();
?process.c
#include<string.h>#include<unistd.h>#include"process.h"#define NUM 101#define SSTYLE '='void prcess_v1(){char buffer[NUM];memset(buffer, 0, sizeof(buffer));char* lable = "|/-\\";int len = strlen(lable);int cnt = 0;while(cnt <= 100){printf("[%-100s][%d%%][%c]\r", buffer, cnt, lable[cnt%len]);fflush(stdout);buffer[cnt] = SSTYLE;cnt++;usleep(3000);}printf("\n");}
main.c
#include"process.h" #include<stdio.h>int main() {process_v1();return 0; {
version-2
process.h
#pragma once #include<stdio.h>void FFlushProcess(double current, double total); void process_v1();
process.c
#include<string.h>#include<unistd.h>#include"process.h"#define NUM 101#define SSTYLE '=' void FFlushProcess(double current, double total) { char buffer[NUM]; memset(buffer, 0, sizeof(buffer)); const char* lable = "|\\-/"; int len = strlen(lable); double rate = current / total; int cnt = rate * 100; int i = 0; for(;i < cnt; i++) { buffer[i] = SSTYLE; } printf("[%-100s][%lf%%][%c]\r", buffer, rate*100, lable[cnt%len]); fflush(stdout); }
main.c
#include"process.h"#include<stdio.h>double speed = 1.0;double total = 1024.0;void DownLoad(){double current = 0;while(current <= total){FFlushProcess(current, total);usleep(3000); //下載的數據 current += speed;}printf("\ndownload %.2lfMB Done\n", current);}int main(){ DownLoad();//prcess_v1();return 0;}
?結果:倒計時符的打印結果