换行(\n)和回车(\r)的区别
<\r>回车(carriage return):即每次打印完使光标回到最开始位置
<\n>换行(line feed):换到当前行的下一行,即光标指向下一行最开始的位置
缓冲区概念
缓冲区分为:无缓冲、行缓冲、全缓冲。
无缓冲:表示的是没有缓冲,可以将信息立马显现出来,典型代表是标准错误流stderr。
行缓冲:表示的是输入输出遇到换行才执行真正的I/O操作。典型的代表是键盘的操作。
全缓冲:表示的是输入输出写满缓冲区才执行I/O操作。典型的代表是磁盘的读写
行缓冲区
先看3个实例
1:
#include <stdio.h>
int main()
{
printf("hello Makefile!\n");
sleep(3);
return 0;
}
什么现象?
2:
#include <stdio.h>
int main()
{
printf("hello Makefile!");
sleep(3);
return 0;
}
什么现象?
#include <stdio.h>
int main()
{
printf("hello Makefile!");
fflush(stdout);
sleep(3);
return 0;
}
什么现象?
对应结果如下:
1.
hello makefile!
[cyan@localhost linux]$
先打印hello makefile! 三秒后换行打印[cyan@localhost linux]$
2.
hello makefile![cyan@localhost linux]$
停顿3秒后在同一行打印hello makefile![cyan@localhost linux]$
3.
hello makefile![cyan@localhost linux]$
先打印hello makefile!3秒后在同一行打印[cyan@localhost linux]$
结论:printf是一个行缓冲函数,先写到缓冲区,满足条件后,才将缓冲区刷到对应文件中,刷新缓冲区的条件如下:
(1)缓冲区填满;
(2)写入的字符中有‘\n’ ,’\r’;
(3)调用fflush手动刷新缓冲区;
(4)调用scanf要从缓冲区中读取数据时,也会将缓冲区内的数据刷新;
满足上面4个条件之一缓冲区就会刷新
fflush
fflush,函数名, 清除读写缓冲区,需要立即把输出缓冲区的数据进行物理写入时。
fflush(stdin)刷新标准输入缓冲区,把输入缓冲区里的东西丢弃[非标准]
fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上
usleep
usleep函数能把进程挂起一段时间, 单位是微秒(千分之一毫秒)。本函数可暂时使程序停止执行。头文件:<unistd.h>
进度条代码实现
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <string.h>
4
5 void ProcBar(){
6 int rate = 0;
7 char str[102];
8 memset(str,0,sizeof(str));
9 const char* ptr = "-\\|/";
10 while(rate <= 100){
11 str[rate] = '=';
W> 12 printf("\e[32m[%-100s][%d\%][%c]\r",str,rate,ptr[rate%4]);
13 usleep(100000);
14 fflush(stdout);
15 ++rate;
16 }
17 printf("\n");
18 }
19
20 int main(){
21 ProcBar();
22 return 0;
23 }
彩色输出参考:[http://www.cnblogs.com/frydsh/p/4139922.html]
前景色 | 字体颜色 |
---|---|
“\e[30m” | 灰色 |
“\e[31m” | 红色 |
“\e[32m” | 绿色 |
“\e[33m” | 黄色 |
“\e[34m” | 蓝色 |
“\e[35m” | 紫色 |
“\e[36m” | 淡蓝色 |
“\e[37m” | 白色 |