使 std::fstream 写入文件末尾,但从头开始读取

Make std::fstream write to end of file but read from beginning

本文关键字:从头开始 读取 文件 std fstream      更新时间:2023-10-16

标题很好地解释了这一点。我有一个截断并写入的文件(作为控制文件初始内容的测试(。然后我想对该文件进行读/写操作。具体来说,我想写到文件的末尾,但从头开始阅读。

程序:

// (1) Make an initial file (truncated std::ofstream) with some contents
// (2) Close initial file stream
// (3) Re-open file with read and write permissions (std::fstream)
// (4) Set stream read pointer to beginning of file
// (5) Set stream write pointer to the end of file

这在某种程度上与问题一起暗示,但是我应该使用什么std::fstream::openmode按位参数来打开文件(或者默认std::fstream::in | std::fstream::out是否足够好(?

fstream 没有单独的读取和写入位置,在从读取更改为写入时需要查找。

seekgseekp都调用pubseekpos对于fstream输入和输出执行相同的操作:https://en.cppreference.com/w/cpp/io/basic_filebuf/seekpos。

根据您的使用案例,同一文件上的单独读取和写入流可能有效。