c++fstream

Why std::fstream::write() modifies tellg()?


Executing the following code

#include <iostream>
#include <fstream>

int main() {
    std::fstream fs{"/dev/shm/test.bin", std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc};
    std::cerr << "open: "<<  fs.is_open()
              << " good: " << fs.good()
              << " tellg: "<< fs.tellg()
              << " tellp: " << fs.tellp() 
              << std::endl;
    
    // writes "12" in binary
    fs.write("123", 2);

    std::cerr << "open: "<<  fs.is_open()
              << " good: " << fs.good()
              << " tellg: "<< fs.tellg()
              << " tellp: " << fs.tellp() 
              << std::endl;

    return 0;
}

Prints

open: 1 good: 1 tellg: 0 tellp: 0
open: 1 good: 1 tellg: 2 tellp: 2

Why does tellg() change? Shouldn't tellg() still be 0 since I have not performed any reads?


Solution

  • In the case of std::fstream, it holds a joint file buffer representing both the get and put area respectively. The position indicator that marks the current position in the file is affected by both input and output operations.

    As a result of this, in order to perform I/O correctly on a bidirectional stream, when you perform a read after a write or vice-versa, the stream should be repositioned back with seekg or seekp.