Search code examples
c++fstreamflush

Flush function in cpp


I have looked up the definition of the function flush in C++, and I got some really satisfactory answers, but I recently came across the following code, and I can't seem to understand if the use of flush is making much of a difference here, it seems that the code is giving a valid output even without the use of flush. Please help out!

#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 updated\n";
   fp.seekg(0);
   while(fp.read((char *)&p,sizeof(p))) {
                  p.display();
   }
   fp.close();
   return 0;
 }

Solution

  • The std::cout and std::cin are tied

    The tied stream is an output stream object which is flushed before each i/o operation in this stream object.

    By default, the standard narrow streams cin and cerr are tied to cout, and their wide character counterparts (wcin and wcerr) to wcout. Library implementations may also tie clog and wclog.

    As for the:

    fp.write((char *)&p,sizeof(p))<<flush;
    cout<<"\nrecord updated\n";
    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)))