cpp中的Flush函数

Flush function in cpp

本文关键字:函数 Flush 中的 cpp      更新时间:2023-10-16

我已经在c++中查找了flush函数的定义,并且我得到了一些非常令人满意的答案,但是我最近遇到了以下代码,我似乎无法理解是否使用flush在这里产生了很大的不同,似乎代码即使没有使用flush也会给出有效的输出。请帮忙!

#include <iostream>
using namespace std;
class person {
public:
    int ph_no;
    char name[50];
    void accept() {
        cout<<"nEnter name";
        cin>>name;
        cout<<"nenter ph_no";
        cin>>ph_no;
    }
    void display() {
        cout<<"name:"<<name<<"n";
        cout<<"phone_no:"<<ph_no<<"n" ;
    }
};
int main() {
 // a few other functions to create file and read file &c &c.
   person p;
   int pno,pos,choice,offset,i;
   fstream fp;
   char name[20];
   cout<<"n enter name";
   cin>>name;
   fp.open("d:\test.dat",ios::out|ios::in|ios::ate|ios::binary);
   fp.seekg(0,ios::beg);
   pos=-1;
   i=0;
   while(fp.read((char *)&p,sizeof(p))) {
      if((strcmp(name,p.name))==0) {
                           pos=i;
                           break;
      }
      i++;
   }
   offset=pos*sizeof(p);
   fp.seekp(offset);
   cout<<"ncurrent phno:"<<p.ph_no;
   cout<<"nenter new phone no";
   cin>>pno;
   p.ph_no=pno;
   fp.write((char *)&p,sizeof(p))<<flush;
   cout<<"nrecord updatedn";
   fp.seekg(0);
   while(fp.read((char *)&p,sizeof(p))) {
                  p.display();
   }
   fp.close();
   return 0;
 }

std::coutstd::cintied

绑定流是this流对象在每次i/o操作之前刷新的输出流对象。

默认情况下,标准窄字符流cincerr绑定到cout,它们的宽字符对应(wcinwcerr)绑定到wcout。库实现也可以绑定clogwclog

至于:

fp.write((char *)&p,sizeof(p))<<flush;
cout<<"nrecord updatedn";
fp.seekg(0);
// the next read will return the correct info even without the
// prev flush because:
// - either the seekg will force the flushing, if the seek-ed
//   position is outside the buffer range; *or*
// - the seekg pos is still inside the buffer, thus no 
//   I/O activity will be necessary to retrieve that info
while(fp.read((char *)&p,sizeof(p)))

Flush强制任何缓冲输出实际输出到设备。为了提高性能,c++通常会缓冲IO。这意味着它将一些数据保存在内存中,并等待,直到有更大的数据量,才与输出设备进行通信。通过减少与设备的通信,每次使用大量的数据,您的IO速度会快得多。

缓冲可能在交互情况下导致问题。如果您的用户提示位于缓冲区中,而不显示给用户,则用户可能会有点困惑。因此,当您需要确保实际显示最后的输出时,可以使用flush.