返回顶部

收藏

用setvbuf实现setbuf并打印缓冲状态消息

更多
#include <stdio.h>
#include <stdlib.h>
#ifndef BUFSIZ
#define BUFSIZ 1024
#endif

void pr_stdio(const char * name, FILE * fp);
void mybuf(FILE *fp,char *buf);

int main()
{
    char buf[BUFSIZ];

    FILE *fp;

    if((fp=fopen("1","w")))
    {
        mybuf(stderr,buf);
        pr_stdio("stderr",stderr);
        mybuf(stdin,NULL);
        pr_stdio("stdin",stdin);
        mybuf(stdout,buf);
        pr_stdio("stdout",stdout);
        mybuf(fp,NULL);
        pr_stdio("1",fp);
        mybuf(fp,buf);
        pr_stdio("1",fp);
    }

    fclose(fp);
    return 0;
}

void mybuf(FILE *fp,char *buf)
{
    if(buf==NULL){
        if(setvbuf(fp,buf,_IONBF,BUFSIZ))
        {
            perror("setvbuf error");
            exit(-1);
        }
        printf("no buf\\n");
 &#129;   }else{
        if(fp==stderr){
            if(setvbuf(fp,buf,_IONBF,BUFSIZ))
            {
                perror("setvbuf error");
                exit(-1);
            }
            printf("no buf\\n");
        }
        else if(fp==stdin||fp==stdout)
        {
            if(setvbuf(fp,buf,_IOLBF,BUFSIZ))
            {
                perror("setvbuf error");
                exit(-1);
            }
            printf("line buf\\n");
        }
        else
        {
            if(setvbuf(fp,buf,_IOFBF,BUFSIZ))
            {
                perror("setvbuf error");
                exit(-1);
            }
            printf("full buf\\n");
        }
    }
}

void pr_stdio(const char * name, FILE * fp)
{
    printf("stream = %s.",name);

    if(fp->_IO_file_flags & _IO_UNBUFFERED)
        printf("unbuffered");
    else if(fp->_IO_file_flags & _IO_LINE_BUF)
        printf("line buffered");
    else
        printf("fully buffereded");
    printf(",buffered size = %d\\n",fp->_IO_buf_end-fp->_IO_buf_base);
}
//该片段来自于http://outofmemory.cn

标签:c++,基础

收藏

0人收藏

支持

0

反对

0

发表评论