Reputation: 24596
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?
Upvotes: 3
Views: 572
Reputation: 31718
Have a look at fbufmode() from gnulib which attempts to do this portably
Upvotes: 2
Reputation: 122383
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.
Upvotes: 3