Reputation: 401
I'm trying to write a small program to find the buffer size of an open file stream. After searching around a little bit, I found the __fbufsize() function. This is the code I wrote:
#include <stdio.h>
#include <stdio_ext.h>
void main() {
FILE *f;
int bufsize;
f = fopen("test.txt","wb");
if (f == NULL) {
perror("fopen failed\n");
return;
}
bufsize = __fbufsize(f);
printf("The buffer size is %d\n",bufsize);
return;
}
I get the buffer size as zero. I'm a bit confused as to why this is happening. Shouldn't the stream be buffered by default? I get a non-zero value if I use setvbuf with _IOFBF before calling fbufsize.
Upvotes: 6
Views: 10204
Reputation: 754860
Note that the correct return type for main()
is int
, not void
.
This code compiles on Linux (Ubuntu 14.04 derivative tested):
#include <stdio.h>
#include <stdio_ext.h>
int main(void)
{
FILE *f;
size_t bufsize;
f = fopen("test.txt", "wb");
if (f == NULL)
{
perror("fopen failed\n");
return -1;
}
bufsize = __fbufsize(f);
printf("The buffer size is %zd\n", bufsize);
putc('\n', f);
bufsize = __fbufsize(f);
printf("The buffer size is %zd\n", bufsize);
fclose(f);
return 0;
}
When run, it produces:
The buffer size is 0
The buffer size is 4096
As suggested in the comments, until you use the file stream, the buffer size is not set. Until then, you could change the size with setvbuf()
, so the library doesn't set the buffer size until you try to use it.
The macro BUFSIZ
defined in <stdio.h>
is the default buffer size. There's no standard way to find the buffer size set by setvbuf()
. You need to identify the platform you're working on to allow useful commentary on __fbufsize()
as a function (though it seems to be a GNU libc extension: __fbufsize()
).
There are numerous small improvements that should be made in the program, but they're not immediately germane.
Upvotes: 12
Reputation: 2440
__fbufsize
man page says:
The
__fbufsize()
function returns the size of the buffer currently used by the given stream.
so I think this is buffer size used by the stream.
Upvotes: 1