3

I have the following code snippet :

ofile.open("New1.dat",ios::app|ios::binary|ios::ate);
long bytes = ofile.tellp()/sizeof(t);
cout<<ofile.tellp()<<endl;    //line 1
t.input(bytes);
ofile.write((char *)&t,sizeof(t));
ofile.close();

When I remove ios::app or ios::ate, the output of line 1 is 0, howeever only when both of them are together, they give the correct file location. Why does this happen? P.S. I know the difference between ios::app and ios::ate.

Thanks in advance!

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43

1 Answers1

5

From std::ios::openmode (Section 27.5.3.1.4 of C++11)

std::ios::app means to seek to the end of stream before each write. So stream may be not be at end before any write operation. No matter where the pointer is (0 or somewhere else) writing is always done at end. (Implicit seek to end before each write operation)

on the other hand std::ios::ate means to seek to the end of stream immediately after open and thus is guaranteed to return the size of file.

Further reading: C++ Filehandling: Difference between ios:app and ios:ate?

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100