This is the mail archive of the mailing list for the glibc project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Stream buffering and flushing behaviour

On 07/07/2015 11:39 AM, Marc-André Lureau wrote:
> Hi
> I am wondering how best to solve the following:
> #include <stdio.h>
> #include <assert.h>
> void main()
> {
>     FILE *f;
>     char foo[4096];
>     int n;
>     f = fopen("/tmp/test", "a+"); /* qemu does fdopen */
>     assert(f);
>     fwrite("Hello World!\n", 1, 13, f);
>     n = fread(foo, 1, READ_SIZE, f);
>     fprintf(stderr, "eof?%d %d", feof(f), n);
>     fseek(f, 0, SEEK_SET);
>     n = fread(foo, 1, sizeof(foo), f);
>     fprintf(stderr, "eof?%d %d", feof(f), n);
> }
> with READ_SIZE >= 4096, there is no implicit flush taking place, while
> with READ_SIZE < 4096 (13 for ex), it does flush to disk and
> subsequent read after seek will return the expected buffer.

Do you mean `fread after fseek`?

> According to glibc manual
> flushing should happen "
> Whenever an input operation on any stream actually reads data from its
> file.", but in the case the requested buffer is too large, you can see
> it doesn't. I am a bit dubious about what best to do to have the
> second read "correct". Should the program track the read/write mode
> and when switching, do an explicit fflush()?

I don't see anything. Do you have a test case that shows the problem?
Expected and observed results?

> thanks a lot for your help
> (fwiw, this is related to the following qemu-ga bug

If all of your operations are through streams you should never lose
any data, and the operations should appear to you as if they had been

The only time you ever have to follow any kind of rules is when switching
between fd and stream based IO [1].


[1] 2.5.1 Interaction of File Descriptors and Standard I/O Streams

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]