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

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

标题说明得很好。我有一个要截断并写入的文件(作为控制文件初始内容的测试)。然后,我想对该文件进行读/写操作。具体来说,我想写入文件的末尾,但要从头开始读取。

步骤:

// (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是否足够好?]]

c++ file file-io fstream
1个回答
0
投票

fstream没有从读写更改为单独的读写位置。

[seekgseekp都调用pubseekpos,对于fstream,这对于输入和输出都相同:https://en.cppreference.com/w/cpp/io/basic_filebuf/seekpos

取决于您的用例,可以在同一文件上使用单独的读写流。

© www.soinside.com 2019 - 2024. All rights reserved.