I'm reading blocks of data from the file, but not all at once (ex. 3 bytes per read/write) and then write same 3 bytes back to file to the very same position inside a file, and then continue looping until there are no more blocks to read.
In other words I'm trying to rewrite the file by it's very contents.
However there is a problem that final output isn't the same as it was in the beginning.
Following sample code reads 3 bytes per iteration from a file "sample.txt", file contents are simple:
0123456789
after reading data and writing data back to file, the contents are:
012345345345
As you see data doesn't get rewritten correctly for some reason.
#include <fstream> #include <iostream> using namespace std; #define BLOCK_SIZE 3 int main() { // open file fstream file; file.open("sample.txt", ios::binary | ios::out | ios::in); // determine size and number of blocks to read file.seekg(0, ios::end); streampos size = file.tellg(); int blocks = size / BLOCK_SIZE; cout << "size:\t" << size << endl; if (size % BLOCK_SIZE != 0) { ++blocks; } cout << "blocks:\t" << blocks << endl; // return to beginning file.seekg(ios::beg); // we will read data here unsigned char* data = new unsigned char[BLOCK_SIZE]; streampos pos; // read blocks of data and write data back for (int i = 0; i < blocks; ++i) { pos = file.tellg(); cout << "before read:\t" << pos << endl; // read block file.read(reinterpret_cast<char*>(data), BLOCK_SIZE); cout << "after read:\t" << file.tellg() << endl; // write same block back to same position file.seekp(pos); cout << "before write:\t" << file.tellg() << endl; file.write(reinterpret_cast<char*>(data), BLOCK_SIZE); cout << "after write:\t" << file.tellg() << endl; // reset buffer memset(data, 0, BLOCK_SIZE); } file.close(); delete[] data; cin.get(); return 0; } Do you see what could be the reason for bad overwrite?
EDIT: Sorry, I can't see how the linked duplicate answers my question, I'm simply unable to apply given answer to the code above.
seekgbefore reading as stated in the duplicate, works for me in visual studio