Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when I allocate memory space for line buffering and the lines of the stream have more bytes than the buffer space?

Tags:

c

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);
}
like image 949
Algo Avatar asked Dec 04 '25 14:12

Algo


1 Answers

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.

like image 140
Barmar Avatar answered Dec 06 '25 06:12

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!