Question

Is there a portable way to retrieve the buffer size used by a stream?

Searching posts online, I've found that glibc has a method:

size_t __fbufsize (FILE *stream)

However, this will only work if I'm using glibc.

It seems that another option is to use the macro BUFSIZ and the flags _IONBF and _IOLBF:

void print_buffering(FILE * fp)
{
    if (fp->_flags & _IONBF)
    {
        printf("No buffering\n");
    }
    else if (fp->_flags & _IOLBF)
    {
        printf("Line buffering - buffer size: %d\n", BUFSIZ);
    }
    else
    {
        printf("Full buffering - buffer size: %d\n", BUFSIZ);
    }
}

Relying on BUFSIZ suggests that the buffer size will always be a constant. Is this always the case?

Was it helpful?

Solution

Relying on BUFSIZ suggests that the buffer size will always be a constant. Is this always the case?

No, it's not.

In the call to setvbuf

int setvbuf(FILE * restrict stream, char * restrict buf, int mode, size_t size);

You can choose the value for size yourself. (Although you may choose to use BUFSIZE) The macro BUFSIZE only works when you call setbuf

void setbuf(FILE * restrict stream, char * restrict buf);

It is equivalent to the setvbuf function invoked with the values _IOFBF for mode and BUFSIZ for size, or (if buf is a null pointer), with the value _IONBF for mode.

OTHER TIPS

Have a look at fbufmode() from gnulib which attempts to do this portably

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top