I'm getting behavior with seekg()
that I don't understand. I avoid the C++ stream libraries as much as possible, so I'm sure I'm just missing something simple.
The problem happens when calling seekg()
as an index into the file. I would expect it to put me at that absolute offset, but the results I'm getting back are not what I'd expect.
Consider the following code:
ifstream fileStream;
//fileStream.open("source/test.txt"); // same behavior in ascii mode
fileStream.open("source/test.txt", ios_base::in | ios_base::binary);
if (!fileStream.is_open())
{
cout << "Failed to open file.\n";
return 1;
}
for (streamoff i = 0; i < 10; ++i)
{
char c = 0;
fileStream.seekg(i, ios::beg);
auto pos = fileStream.tellg();
fileStream >> c;
cout << "Pos: " << pos << " is " << c << "\n";
}
The file in question looks like this:
123
456
789
I would expect this to print something like:
Pos: 0 is 1
Pos: 1 is 2
Pos: 2 is 3
Pos: 3 is
Pos: 4 is 3
Pos: 5 is 4
Pos: 6 is 5
Pos: 7 is
Pos: 8 is 6
Pos: 9 is 7
Instead it prints:
Pos: 0 is 1
Pos: 1 is 2
Pos: 2 is 3
Pos: 3 is 4
Pos: 4 is 4
Pos: 5 is 4
Pos: 6 is 5
Pos: 7 is 6
Pos: 8 is 7
Pos: 9 is 7
Note that this happens even when setting passing ios_base::binary
to open()
.
I'm on MSVC 17.3.6.
Finally, I know this is not the way to read a file. I would never actually do this in production, preferring to read the entire file into memory to process internally. I'm just trying to understand what's happening here and why it's not behaving as I would expect.