对 std::ofstream 进行空文件检查
Empty file check on std::ofstream
我一直在用std::ofstream
来写作。我打开文件,根据某些条件执行一些操作并关闭它。
假设稍后我想检查是否有任何内容真的写入文件。std::ofstream
没有可用的 is_emtpy() 类型的简单检查。
我认为的一种方法是使用独立于std::ofstream
的stat
方式。
想知道其他人是怎么做到的吗?
标准输出流提供了一种可用于确定当前写入位置的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
。
相关文章:
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 如何检查函数是否在LLVM Instrumentation pass的ModulePass的系统头文件中定义?
- 如何检查流中文件的下一个单词是否为 alpha?
- 如何检查文件是否已存在于 fstream C++中
- CocoaPod - 在头文件中使用 C++ 时出现 Podspec 检查错误
- 如何使用 ifstream 检查文件中变量的类型?
- 检查特定txt文件中的项目是否符合"名称编号USACO"中的约束
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 文件存在时的最新检查声明生成输入"is missing"
- 如何检查C++中是否存在文件?
- 检查cpp文件中是否使用了变量
- C++ 如何检查哪些单词不在 2 个类似文件中
- 如何检查文件复制和写入是否成功
- 如何检查二进制文件中是否存在字符串
- 如何在SWIG接口文件中检查Lua版本
- 检查特定目录中是否存在与文件匹配的 abc* 的最佳方法
- 如何检查从键盘输入的特定整数值是否存在于C++文件中的一行或多行中
- 功能调用,该函数从文本文件-C 检查输入正确性
- 如何在C++中进行文件检查
- 使用vim中的语法启用cpp头文件检查