为什么我需要刷新我的I / O流,以获得正确的结果呢? [英] Why do I need to flush my I/O stream to get the correct result?

查看:195
本文介绍了为什么我需要刷新我的I / O流,以获得正确的结果呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么低于code不起作用?我的意思是,它显示在控制台输出各种奇怪的字符。

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;
    }
}

不过,code以下效果很好。

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,80,pFile);
        puts (mybuffer);
        fclose (pFile);
        return 0;
    }
}

为什么需要,为了得到正确的结果刷新流?

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

推荐答案

由于标准是这样说的(§7.19.5.3/ 5):

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

当一个文件被打开与更新模式
  (+作为第二或第三字符
  在mode参数的上述名单
  值),输入和输出可以是
  上相关的数据流执行。
  然而,输出不得直接
  依次输入无
  干预调用fflush
  功能或文件的定位
  功能(fseek的,fsetpos或倒带),
  和输入不应直接
  其次是输出无
  干预调用文件定位
  功能,除非输入操作
  遇到档案结尾。

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.

还有一个原因:输出和输入通常单独缓冲。当有一个冲洗或寻求,它同步与文件缓冲区,但除此之外,它可以让他们摆脱同步。这genarally提高性能(例如,当你做一读,它没有检查你从因为数据已经写入读取位置是否被读入缓冲区)。

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).

这篇关于为什么我需要刷新我的I / O流,以获得正确的结果呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆