当 C++ 创建
std::ofstream
时,它会立即隐式创建底层文件。
我完全同意这种行为,除非我有一个代码,只有在运行期间才能看到是否会产生任何数据。
因此,我想避免在没有数据发送给空文件时创建空文件(事务完整性:没有数据,文件系统上没有更改)。
我看到两种我不太喜欢的方法:
tellg()
),如果流为空,则删除文件。我不喜欢创建和删除文件(有时文件很多)并且remove
操作本身承担了太多责任。std::stringstream
,收集输出并创建std::ofstream
并仅在字符串流不为空的情况下复制内容。好多了,但仍然需要临时内存分配,这可能很大。有更好的解决方案吗?我是否缺少一些想法?
代码形式:
#include <fstream>
int main()
{
std::ofstream ofs("file.txt");
// Some code that might or might not output to ofs
// It would be nice if file is not created if no data sent to ofs
}
使用带有文件名的
构造函数创建
std::ofstream
对象,打开文件。您可以通过仅在实际需要写入时通过 open
提供文件名来解决此问题。
#include <fstream>
int main()
{
std::ofstream ofs;
// determine whether you need to write
if (/*need_to_output*/) {
ofs.open("file.txt");
}
// write to ofs
}