If you ....?

When you call an ofstream object's open member function, the specified file will be erased if it already exists...

is that right? :S
anyone?
That depends on what the second argument to the function is. If you just call the open member function with one parameter then yes. But if you call it with "std::ofstream::app" then you will keep the data that was previously entered.
> When you call an ofstream object's open member function, the specified file will be erased if it already exists...

That is the default. We can use the open mode of the stream to get the behaviour we want.
http://stdcxx.apache.org/doc/stdlibug/30-3.html#3031

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <fstream>

int main ()
{
    // create the file "filea.txt" if it does not exist,
    // truncate it to zero length if it does exist.
    std::ofstream filea( "filea.txt" ) ;
    // equivalent to std::ofstream filea( "filea.txt", std::ios_base::out ) ;
    // for output streams, that is eqivalent to:
    // std::ofstream filea( "filea.txt", std::ios_base::out | std::ios_base::trunc ) ;
    

    // create the file "fileb.txt" if it does not exist,
    // do not truncate it to zero length if it does exist.
    // all output is written at the current end of the file,
    // we can never write to a position other that the current end of the file
    std::ofstream fileb( "fileb.txt", std::ios_base::out | std::ios_base::app ) ;
    

    // create the file "filec.txt" if it does not exist,
    // do not truncate it to zero length if it does exist.
    // the initial file position is at the end of the file,
    // however, we can seek to another position and write there.
    std::ofstream filec( "filec.txt", std::ios_base::out | std::ios_base::ate ) ;
    

    // open the file "filed.txt" if it does exist, do not truncate it to zero length
    // the operation fails if the file does not exist (the stream goes to a failed state).
    // the initial file position is at the beginning of the file,
    std::ofstream filed( "filed.txt", std::ios_base::out | std::ios_base::in ) ;
}


The effect of the open mode is identical for the open() member function.
Topic archived. No new replies allowed.