C语言学习: 文件流的缓冲

没有缓冲

有了缓冲

 

 创建file变量时,传入的参数:

 

可以用fflush, 清空缓冲区,让缓冲区内存的数据立刻打印出来。

 1 #include <stdio.h>
 2 #include <io_utils.h>
 3 #include <errno.h>
 4 #include <string.h>
 5 
 6 char std_buffer[BUFSIZ];
 7 
 8 int main() {
 9   setbuf(stdout, std_buffer);
10 
11   FILE *file = fopen("CMakeLists.txt", "r");
12   char buf[8192];
13   //setbuf(file, NULL);
14   if (file) {
15     setvbuf(file, buf, _IOLBF, 8192);
16     //...
17     puts("Open successfully.");
18     int err = ferror(file);
19     PRINT_INT(err);
20 
21     int eof = feof(file);
22     PRINT_INT(eof);
23     fflush(stdout);
24     fclose(file);
25   } else {
26     PRINT_INT(errno);
27     puts(strerror(errno));
28     perror("fopen");
29   }
30   return 0;
31 }
View Code

 

posted @ 2023-02-12 15:05  泥古拉斯赵四  阅读(23)  评论(0编辑  收藏  举报