这段代码只为行缓冲分配了 10 个字节,并读取了一个第一行有 45 个字节的文件。当它运行时,程序会读取所有 45 个字节,而不仅仅是我预期的前 10 个字节,那么setvbuf实际上做了什么?
#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);
}