c++filebinaryfstreamoverwrite

How to overwrite a portion of a binary file using C++?


I have a binary file, and let's say at byte 11 to byte 14, representing an integer = 100. Now I want to replace that integer value = 200 instead of the existing one.

How can I do that using C++? Thanks T.


Solution

  • Google is your friend. Searching for "C++ binary files" will give you some useful pages, such as: This useful link

    In short, you can do something like this:

    int main() 
    { 
      int x; 
      streampos pos; 
      ifstream infile; 
      infile.open("silly.dat", ios::binary | ios::in); 
      infile.seekp(243, ios::beg); // move 243 bytes into the file 
      infile.read(&x, sizeof(x)); 
      pos = infile.tellg(); 
      cout << "The file pointer is now at location " << pos << endl; 
      infile.seekp(0,ios::end); // seek to the end of the file 
      infile.seekp(-10, ios::cur); // back up 10 bytes 
      infile.close(); 
    } 
    

    That works for reading. To open a file for output:

    ofstream outfile;
    outfile.open("junk.dat", ios::binary | ios::out);
    

    Combining those two and adjusting for your specific needs shouldn't be too hard.