【Linux】文件缓冲区(setbuf,setvbuf)

行缓冲区:

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

全缓冲区:

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

无缓冲区:

  1. 将直接调用系统IO刷新缓冲区
  2. 举例:stderr

 

#include                                                                                                                                                                                                        
#include 
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;
}

 

你可能感兴趣的:(后端)