This C++ code is intended to move the data from 67 ~ 69 to 70 ~ 72 in the file:
#include <fstream>
#include <iostream>
int main() {
std::fstream file("test", std::ios::out);
file.close();
file.open("test", std::ios::binary | std::ios::in | std::ios::out);
for (char i = 0; i < 127; ++i)
file.write(&i, 1);
file.seekp(70);
file.seekp(-3, std::ios::cur);
char s[100];
for (int i = 0; i < 100; ++i)
s[i] = '\0';
file.read(s, 3);
for (int i = 0; i < 3; ++i)
std::cout << (int)s[i] << " ";
std::cout << std::endl;
file.write(s, 3);
file.seekp(-3, std::ios::cur);
file.read(s, 3);
for (int i = 0; i < 3; ++i)
std::cout << (int)s[i] << " ";
std::cout << std::endl;
}
The content of s
should be the same in the two times I read it, just as the output if we compile the code in g++:
67 68 69
67 68 69
But the result in Visual Studio is different:
67 68 69
70 71 72
Is there any undefined behavior involved that leads to the bug? How should I fix it?