Detecting FILE * buffering

This C program tells you what type of buffering is being used for open files: no buffering, line buffering, or full buffering. Running it normally gives output like this:

stream = stdin, fully buffered, buffer size = 0
stream = stdout, line buffered, buffer size = 4096
stream = stderr, unbuffered, buffer size = 0
stream = /etc/motd, fully buffered, buffer size = 4096

This method using the _flags member of the FILE structure comes from "Advanced Programming in the UNIX Environment" by W. Richard Stevens (ISBN 0-201-56317-7). Although _IOLBF and friends are part of the standard, I have not been able to confirm that the _flags variable is in the C standard, so this method may be Unix-specific.

#include <stdio.h>
#include <err.h>

void pr_stdio (const char * name, FILE * fp)
{
    printf ("stream = %s, ", name);
    if (fp->_flags & _IONBF) {
        printf ("unbuffered");
    }
    else if (fp->_flags & _IOLBF) {
        printf ("line buffered");
    }
    else {
	printf ("fully buffered");
    }
    printf (", buffer size = %d\n", fp->_bf._size);
}

int main ()
{
    FILE * fp;
#if 0
    fputs ("enter any character\n", stdout);
    if (getchar () == EOF) {
        err (1, "getchar error");
    }
    fputs ("one line to standard error\n", stderr);
#endif
    pr_stdio ("stdin", stdin);
    pr_stdio ("stdout", stdout);
    pr_stdio ("stderr", stderr);

    fp = fopen ("/etc/motd", "r");
    if (fp == 0) {
        err (1, "fopen error");
    }
    if (getc (fp) == EOF) {
        err (1, "getc error");
    }
    pr_stdio ("/etc/motd", fp);
    return 0;
}

Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer