繁体   English   中英

在写入文件时,如何根据标志附加或不附加?

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

我知道这行不通,但它应该清楚我想要做什么:

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

我怎样才能做到这一点?

一种选择,特别是如果 if/else 中有额外的逻辑,是使用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);

会做的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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