Search code examples
c++filestreamfstream

Is there any bug inducing feature when reading and writing using the same fstream object in c++


I am trying to learn C++ fstream, ifstream, ofstream. On Half way through my project I learnt that if we are accessing the same file with ofstream and ifstream for read & write, its better to close the streams, before using another.

Like ofstream write_stream(...); ifstream read_stream(....);

 // Accessing pointers using both read_stream, write_stream interchangebly 

  read_stream.read(....);
  write_stream.write(....);

  read_stream.close(); 
  write_stream.close();

///

In the above case, I guess both the stream use the same pointer in the file, so I need to be aware of the pointer movement, so I have to seek each and every time I try to read() or write().

I guess, I am right, so far.

To avoid any more confusion, I have decided to use this format

 fstream read_write_stream("File.bin",ios::in|ios::out|ios::binary);
 read_write_stream.seekp(pos);
 read_write_stream.seekg(pos);
 read_write_stream.tellp();
 read_write_stream.tellg()

 read_write_stream.read(...);
 read_write_stream.write(...);

 read_write_stream.close()

Is there any bug inducing feature, that I should be aware of in the above program??? Please advice


Solution

  • Though I don't know if the standard explicitly refers to this case, I don't think that a C++ compiler can promise you what will happen in the case where you use several streams to change the same external resource (file in this case). In addition to the fstream internal implementation, it depends on the OS and the hardware you're writing to. If I'm correct, it makes this operations, by default, undefined behavior.

    If you use two different streams, most likely each will manage its own put and get pointer, each will have buffering which means that if you don't use flush(), you won't be able to determine what is the order the operations will be done on the file.

    If you use one stream to both read and write, I think the behavior will be predictable and more trivial understand.