How can I append, or not, when writing to a file, based on a flag?

Viewed 74

I know this won't work, but it should make clear what I want to do:

if (append) {
   std::ofstream f(fname, std::ios::app);
} else {
   std::ofstream f(fname);
}
f << stuff; 
//etc;
f.close()

How can I do this?

2 Answers

One option, especially if there is additional logic in the if/else, is to use open:

std::ofstream f;
if (append) {
   f.open(fname, std::ios::app);
} else {
   f.open(fname);
}
f << stuff; 
//etc;
f.close()
Related