- 行缓冲区
- 回车概念
- 换行概念
- 进度条的例子
1.行缓冲区
以下程序有什么区别?
代码一:
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world");
sleep(3);
return 0;
}
代码二:
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world\n");
sleep(3);
return 0;
}
代码三:
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("hello world");
fflush(stdout);
sleep(3);
return 0;
}
代码一等待3s输出hello world,代码二和代码三先输出hello world 再等待三秒。
因为标准I/O库收集每一行的缓冲区的长度是固定的,所以只有填满的了缓冲区,或者遇到换行符,才会进行I/O的操作。
2. \n&&\r
\n 表示换行,另起一行,光标来行首
\r 表示回车,不另起一行,光标来行首
3.进度条的例子
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
const char* a = "/~\\";
char buf[103] = {0};
memset(buf,' ',101);
buf[101] = ']';
buf[102] = '\0';
int i = 0;
for(; i<=100; i++)
{
buf[i] = '#';
printf(" \e[0;31m[%d%%]\e[1;33m[%c]\e[1;32m[%s\r",i,a[i%3],buf);
fflush(stdout);
usleep(500*1000);
}
printf("\ncomplete\n\e[0m");
return 0;
}