This code allocates just 10 bytes for line buffering and reads a file which have a 45 bytes first line. When it runs, the program reads all the 45 bytes not just the first 10 bytes as I expected it to do, so what setvbuf actually did?
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *tst;
tst = fopen("x.log","r");
char *buff = malloc(10); //Just 10 characters
setvbuf(tst, buff, _IOLBF, 10);
char *mystring = malloc(45); //First line of x.log is 45 characters exactly
if ( fgets (mystring, 45, tst) != NULL )
puts(mystring);
fclose (tst);
free(buff);
}
fgets() uses getc() internally, to read one character at a time, until it reads a newline or reaches the limit it was given. Whenever getc() reaches the end of the I/O buffer, it will refill the buffer, so it's not limited to the size set by setvbuf(). Setting a small buffer size just makes it less efficient, but doesn't change the amount of data that can be read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With