samedi 27 juin 2015

fully-buffered stream get flushed when it is not full

I really confused with how exactly a buffer work. So I write a little snippet to verify:

#include<stdio.h>
#define BUF_SIZE 1024 

char buf[BUF_SIZE];
char arr[20];

int main()
{
        FILE* fs=fopen("test.txt","r");
        setvbuf(fs,buf,_IOFBF,1024);
        fread(arr,1,1,fs);
        printf("%s",arr);

        getchar();

        return 0;
}

As you see, I set the file stream fs to fully buffered stream(I know most of the time it would default to fully-buffered. just making sure). And I also set its related buffer to be size 1024, which mean that the stream would not be flushed until it contain 1024 bytes of stuff(right?).

In my opinion, the routine of fread() is that, it read data from the file stream, store it at its buffer buf,and then the data in the buf would be send to the arr as soon as it is full of 1024 bytes of data(right?).

But now, I read only one character from the stream!!And also, there is are only four characters in the file test.txt. why can I find something in the arr in case that there is only one char(I can print that one character out)

Aucun commentaire:

Enregistrer un commentaire