简体   繁体   中英

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

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?

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()
std::ofstream f(fname, append ? std::ios::app : std::ios::out);

will do it.

Reference https://en.cppreference.com/w/cpp/io/basic_ofstream/open

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM