ofstream append?

First I'll show you a simplified version of the code I'm looking at.

1
2
3
4
5
6
7
std::ofstream output;
output.exceptions(std::ios_base::badbit | std::ios_base::failbit);
std::string filename = config.reportFilename;

output.open(filename.c_str());
output << *report;
output.close();


I want to make sure I understand ofstream correctly. In this instance output.open is opening a file for an input stream. Can I assume any existing information in the file will be overwritten? I've tried to look at definitions of ofstream but can't find an explicit "this overwrites existing info" statement. From what I can tell (after experimenting with it) I think it does overwrite info. Can anyone confirm this?

If so, is there a way I can have it append rather than overwrite?

I've tried to find a way to do this (i.e. looking for an output.append() option or similar) but can't seem to find what I'm looking for.

Thanks in advance for the help.

Regards,
Rico
I'm sorry but perhaps I'm just too new to this. I can't see how to actually use that information. I see there is an append option available but the example shown does not elude to any use of options.

How would I put these options to use?
closed account (Lv0f92yv)
By default, opening a file for output will truncate the file (zero-out the file, making it size 0), thus ovveriting it's contents (if any).

From the reference section: filestr.open ("test.txt", fstream::in | fstream::out | fstream::app);

This opens a file for input and output, with the output being appended to the end of the file. It might be simpler to use separate file streams rather than read and write from one (IMO).

You're code: output.open( filename.c_str() ); uses the default open arguments, which are to open it in non-binary mode and truncate.

If you want to append, use output.open( filename.c_str(), ios::out | ios::app );

where app is a member of the ios namespace (hence the ios:: qualifier) that means append.

The reference link above shows the possible options.

Seperate options by the | (bit-operator or) symbol.

Edit: ios::out explicitly says open for output, rather than input. It is usually a good idea to include this even if you are using a specific ofstream or ifstream object, since it helps with readability (and the compiler can catch you doing something stupid in case you forget somewhere in your code).
Last edited on
Thank you for the help Desh - that cleared up a lot.

As an aside: The reference given on this site (the link above) does not give enough information for a beginner to understand how to properly use the functionality - the wording is entirely too convoluted. Is there a website that contains more examples than this one? This website has a lot of c++ references but not nearly enough examples.
Topic archived. No new replies allowed.