Linux 设置文件缓冲区(setbuf,setvbuf)

版权声明:这里将不定期发布一些技术上分享,如对文章有任何意见或者建议,欢迎评论,转载请注明出处。 https://blog.csdn.net/goal_ff/article/details/89922718

行缓冲区:

  1.  默认大小:1024字节;
  2. 遇\n或缓冲区满时,将刷新缓冲区;
  3. 举例:stdin, stdout

全缓冲区:

  1.  默认大小:4096字节;
  2. 缓冲区满时,将刷新缓冲区;
  3. 举例:普通磁盘文件;

无缓冲区:

  1. 将直接调用系统IO刷新缓冲区
  2. 举例:stderr
#include <stdio.h>                                                                                                                                                                                                       
#include <stdlib.h>
int main()
{
    int i;
    FILE *fp;
    char msg[] = "hello,world\n";
    char buf[128];
    if((fp = fopen("setbuf_nobuff.txt","w")) == NULL)
    {
        perror("file open fail");
        exit(-1);
    }
    setbuf(fp,NULL); // NO_BUFF
    fwrite(msg,7,1,fp);
    printf("test setbuf(NULL)\n");
    printf("press enter to continue\n");
    getchar();
    fclose(fp);

    if((fp = fopen("setvbuf_ionbf.txt","w")) == NULL)
    {
        perror("setvbuf_ionbf.txt");
        exit(-1);
    }
    setvbuf(fp,NULL,_IONBF,0);
    fwrite(msg,7,1,fp);
    printf("test setvbuf(_IONBF)\n");
    printf("press enter to continue\n");
    getchar();
    fclose(fp);
    if((fp = fopen("setvbuf_iolbf.txt","w")) == NULL)
    {
        perror("setvbuf_iolbf.txt");
        exit(-1);
    }
    setvbuf(fp,buf,_IOLBF,sizeof(buf));
    fwrite(msg,sizeof(msg),1,fp);
    printf("test setvbuf(_IOLBF)\n");
    printf("press enter to continue\n");
    getchar();
    fclose(fp);

    if((fp = fopen("setvbuf_iofbf.txt","w")) == NULL)
    {
        perror("setvbuf_iofbf.txt");
        exit(-1);
    }
    setvbuf(fp,buf,_IOFBF,sizeof(buf));
    for(i = 0;i < 2;i++)
    {
        fprintf(fp, msg);
    }
    printf("test setbuf(_IOFBF)\n");
    printf("press enter to continue\n");
    getchar();
    fclose(fp);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/goal_ff/article/details/89922718
今日推荐