对 std::ofstream 进行空文件检查

Empty file check on std::ofstream

本文关键字:文件 检查 std ofstream      更新时间:2023-10-16

我一直在用std::ofstream来写作。我打开文件,根据某些条件执行一些操作并关闭它。

假设稍后我想检查是否有任何内容真的写入文件。std::ofstream没有可用的 is_emtpy() 类型的简单检查。

我认为的一种方法是使用独立于std::ofstreamstat方式。

想知道其他人是怎么做到的吗?

标准输出流提供了一种可用于确定当前写入位置的tellp()方法。 返回值的类型和含义是实现定义的,但要使其有用,它必须返回不同的值。

#include <iostream>
#include <fstream>
int main()
{
std::ofstream out{"/tmp/test"};
auto const empty_pos = out.tellp();
std::clog.setf(std::ios_base::boolalpha);
std::clog << "At start: " << (out.tellp() != empty_pos) << 'n';
out << 'c';
std::clog << "After writing 1 char: " << (out.tellp() != empty_pos) << 'n';
}

原则上,每个流的empty_pos可能不同,因此真正可移植的程序会考虑到这一点。

另请注意,这并不一定意味着输出对其他程序可见 - 如果这很重要,请使用std::flush