Ios_base :: ate and tellp ()

#include <fstream>
#include <iostream> 

int main() 
{ 
    const char* fileName = "out1"; 
    std::ofstream fs1(fileName); 
    fs1 << "AAAAAAAAAAA\n"; 
    std::cout << fs1.tellp() << std::endl; 
    fs1.close(); 

    std::ofstream fs2(fileName, std::ios_base::ate); 
    std::cout << fs2.tellp() << std::endl; 
    fs2.close(); 

    return 0;   
}   

      

gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC)

g ++ file02.cpp

./a.out

12 0

Why does fs2.tellp () print 0 but not 12?

+3


source to share


2 answers


When you open a file for output with std::ofstream

, it is truncated unless you set both std::ios_base::in

as and std::ios_base::out

, or you set std::ios_base::app

in the mode parameter.

The mode parameter passed to the constructors std::ofstream

and std::ifstream

is redirected to the std::filebuf::open

member function . Its value determines how the file is opened according to the mapping of the appropriate behavior for the mode parameter to the C library function fopen

. This mapping takes into account all flags other than std::ios_base::ate

. So the display looks like this:

Flag combination: in out trunc app | fopen mode
                        + "w"
                        + + "a"
                                  + "a"
                        + + "w"
                   + "r"
                   + + "r +"
                   + + + "w +"
                   + + + "a +"
                   + + "a +"

(C ++ 03 omitted lines with app

, but out

unset, they are now equivalent to lines with app

and out

both are set.)



Also, if std::ios_base::binary

set, is b

added to the mode equivalent fopen

.

If the combination of the missing flags (ignore std::ios_base::ate

) does not match one of these combinations, then the opening should fail.

Note that it fopen

truncates the file for modes "w"

and "w+"

.

std::ios_base::ate

causes the position to be opened at the end of the file when the file is opened. This will only be in effect if the rest of the mode parameter is such that it does not truncate the open file and the file already exists and has a nonzero size.

+3


source


You don't supply a flag out

when you open the file again for writing. Do it like this:



std::ofstream fs2(fileName, std::ios_base::out | std::ios_base::ate);

      

0


source







All Articles