Reputation: 33
Consider the next code:
#include <iostream>
#include <fstream>
using std::fstream;
int main()
{
fstream file("text.txt", ios::out| ios::in |ios::trunc| ios::binary);
if (!file)
throw"ERROR\n";
char y = 't';
streampos get = file.tellg(); // (static_cast<int>(get) == 0)
streampos put = file.tellp(); // (static_cast<int>(put) == 0)
file.write(&y, sizeof(y)); // I'd assume that it will increment *only* the putting
cursor
get = file.tellg(); // Assumingly, the getting cursor will remain the same:
// (static_cast<int>(get) == 0) . In reality: (static_cast<int>(get) == 1)
put = file.tellp(); // Assumingly and in reality: (static_cast<int>(put) == 1)
return 0;
}
I've been told that the two cursors are independent of each other, and it made sense to me. 2 stream-directions, two cursors. Hence I was very surprised by the results of my checks. I tried to find answers as to why it happens, but the best I could find is this: . Which says:
Both
seekg
andseekp
have the same effect; using either changes the position of the other.
BTW the repeated seekg and seekp aren't needed. You only need to set the position one time to change modes.
But these answers just note the behaviour, and I don't manage to understand the behaviour's reason. Because, why would a fstream file, that's opened for input and output streams, have 1 cursor for its two streams?
Also, there's this answer:
The position indicator that marks the current position in the file is affected by both input and output operations.
When you perform a read after a write or vice-versa, the stream should be repositioned back.
Which I'd like to have an explanation to too. Because, in addition to noting what the other answers note, this answer also notes:
If an input operation hit the end-of-file, performing a write directly thereafter is fine.
Which doesn't make sense either, because what he's saying is that reading directly after the end-of-file, is fine..
All of this is unintelligible for me. Hence my question is: Why does the fstream perfom the way it does? Why when maintaining 2 stream-directions, it has only 1 cursor?
Thanks.
Upvotes: 0
Views: 27