简体   繁体   中英

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

The title explains this fairly well. I have a file that I truncate and write to (as a test to control the initial contents of the file). I then want to do read/write operations with that file. Specifically, I want to write to the end of the file, but read from the beginning.

Procedure:

// (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

This is somewhat implied along with the question, but what std::fstream::openmode bitwise parameters should I use to open the file (or is the default std::fstream::in | std::fstream::out good enough)?

fstream doesn't have separate read and write positions you need to seek when changing from read to write.

seekg and seekp both call pubseekpos which for fstream does the same for both input and output: https://en.cppreference.com/w/cpp/io/basic_filebuf/seekpos .

Depending on your use case a separate read and write stream on the same file might work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM