个人主页:Lei宝啊
愿所有美好如期而遇
目录
换行\n,回车\r

似乎无需多言
这里我们通过例子来简单理解即可,深入理解以后再说

运行结果是什么呢?

先暂停3秒,然后全部输出。
这是因为缓冲区是按照行进行刷新的,在换行的时候会将该行数据刷新到屏幕上,在程序运行结束时会将缓冲区的数据全部刷新,在缓冲区满时也会刷新。
而我们的代码刻意地没有加换行符。
所以我们需要定期刷新,就要用到fflush函数,传stdout,即标准输出,输出到显示屏上。

这一次是打印一次,然后休眠一秒。
- const char *str = "-|\\/";
-
- void process()
- {
- char arr[NUM] = {0};
- arr[0] = SYMBOL;
-
- int cnt = 1;
- while(cnt <= 100)
- {
- printf("[%-100s][%3d%%][%c]\r",arr,cnt,str[cnt%4]);
- fflush(stdout);
- Sleep(100);
- arr[cnt++] = SYMBOL;
- }
- printf("\n");
- }
- #define NUM 104
- #define SYMBOL '#'
-
- const char *str = "-|\\/";
- #define DownLoadSize (1024*1024*1024)
-
- void download()
- {
- srand((unsigned int)time(NULL));
-
- double _rate = 0;
- int total = DownLoadSize;
-
- while(total)
- {
-
- int speed = rand() % (1024 * 1024) * 100;
- total -= speed;
-
- if(total < 0)
- {
- total = 0;
- }
-
- _rate = (DownLoadSize - total) * 1.0 / DownLoadSize * 100;
- process_flush(_rate);
- }
- printf("\n");
-
- }
-
- char arr[NUM] = {0};
- void process_flush(double rate)
- {
- static int cnt = 0;
-
- int temp = (int)rate;
- arr[temp] = SYMBOL;
-
- printf("[%-100s][%.1lf%%][%c]\r",arr,rate,str[cnt%4]);
- fflush(stdout);
- Sleep(100);
-
- cnt++;
- cnt %= 4;
- }
写个主函数调用即可,但是别忘了修改后要make
相较与version2,做了颜色和符号改变
- 4 #define SYMBOL ' '
-
- 51 char arr[NUM] = {0};
- 52 void process_flush(double rate)
- 53 {
- 54 static int cnt = 0;
- 55
- 56 int temp = (int)rate;
- 57 if(temp < 100)
- 58 arr[temp] = SYMBOL;
- 59
- 60 //printf("[\033[0;35;47m%-100s\033[0m][%.1lf%%][%c]\r",arr,rate,str[cnt%4]);
- 61 printf("[\033[0;47m%-100s\033[0m][%.1lf%%][%c]\r","",rate,str[cnt%4]);
- 62 printf("[\033[0;45m%-s\033[0m\r",arr);
- 63
- 64 fflush(stdout);
- 65 usleep(100000);
- 66
- 67 cnt++;
- 68 cnt %= 4;
- 69 }
效果如下:

