如果没有数据发送到std::ofstream,如何避免创建文件?

问题描述 投票:0回答:1

当 C++ 创建

std::ofstream
时,它会立即隐式创建底层文件。

我完全同意这种行为,除非我有一个代码,只有在运行期间才能看到是否会产生任何数据。

因此,我想避免在没有数据发送给空文件时创建空文件(事务完整性:没有数据,文件系统上没有更改)。

我看到两种我不太喜欢的方法:

  1. 查看是否有内容发送到流中 (
    tellg()
    ),如果流为空,则删除文件。我不喜欢创建和删除文件(有时文件很多)并且
    remove
    操作本身承担了太多责任。
  2. 创建
    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
}
c++ std
1个回答
1
投票

使用带有文件名的

构造函数
创建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
}
© www.soinside.com 2019 - 2024. All rights reserved.