前序:
首先先理解一下什么是回车与换行;回车和换行是两个概念,它们不是一个东西;
- 回车:光标回到开始;
- 换行:换到下一行;
如下图:
行缓冲区
如何理解缓冲区问题?
可以认为,缓冲区就是一块内存块,有的输出的内容会先这个缓冲区中,在缓冲区刷新时一起输出到输出端;如下图
如果想让他立马刷新打印怎么办?
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;}
结果:倒计时符的打印结果