开发者

Why do I need to flush my I/O stream to get the correct result?

开发者 https://www.devze.com 2022-12-19 11:05 出处:网络
Why the code below does not work? I mean, it shows all kinds of weird characters on console output. #include <stdio.h>

Why the code below does not work? I mean, it shows all kinds of weird characters on console output.

#include <stdio.h>
char mybuffer[80];
int main()
{
    FILE * pFile;
    pFile = fopen ("example.txt","r+");
    if (pFile == NULL) perror ("Error opening file");

    else {
        fputs ("test",pFile);

        fgets (mybuffer,80,pFile);
        puts (mybuffer);
        fclose (pFile);
        return 0;
    }
}

However, the code below works well.

#include <stdio.h>
char mybuffer[80];
int main()
{
    FILE * pFile;
    pFile = fopen ("example.txt","r+");
    if (pFile == NULL) perror ("Error opening file");

    else {
        fputs ("test",pFile);
        fflush (pFile);    
        fgets (mybuffer开发者_JAVA百科,80,pFile);
        puts (mybuffer);
        fclose (pFile);
        return 0;
    }
}

Why I need to flush the stream in order to get the correct result?


Because the standard says so (§7.19.5.3/5):

When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file.

There is a reason for this: output and input are normally buffered separately. When there's a flush or seek, it synchronizes the buffers with the file, but otherwise it can let them get out of synch. This genarally improves performance (e.g. when you do a read, it doesn't have to check whether the position you're reading from has been written since the data was read into the buffer).


When using a file with a read/write mode you must call fseek/fflush before different i/o operations.

See this answer on why fseek or fflush is always required...


its because C file io works using a buffer. This is only written to disk when you flush it, you write a /n character or you fill the buffer up.

So in the first case, your file contains nothing when you come to read from it.

0

精彩评论

暂无评论...
验证码 换一张
取 消