title: How can I open a file in c++, without erasing its contents and not append it?
body: <p>I am trying to find a way using which I can Edit the contents in a binary file, without reading the whole file.</p>
  
  <p>Suppose this is my file</p>
  
  <pre><code>abdde
  </code></pre>
  
  <p>And I want to make it</p>
  
  <pre><code>abcde
  </code></pre>
  
  <p>I tried following:-
  Attempt 1)</p>
  
  <pre><code>ofstream f("binfile", ios::binary);
  if(f.is_open()){
    char d[]={'c'};
    f.seekp(2,ios::beg);
    f.write(d, 1);
    f.close();
  }
  //the file get erased
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>**c
  </code></pre>
  
  <p>Attempt 2)</p>
  
  <pre><code>ofstream f("binfile", ios::binary | ios::app);
  if(f.is_open()){
    char d[]={'c'};
    f.seekp(2,ios::beg);
    f.write(d, 1);
    f.close();
  }
  //the file simple gets append seekp() does nothing
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>abddec
  </code></pre>
  
  <p>Attempt 3)</p>
  
  <pre><code>ofstream f("binfile", ios::binary | ios::app);
  if(f.is_open()){
    char d[]={'c'};
    f.seekp(2);
    f.write(d, 1);
    f.close();
  }
  //same as before the file simple gets append seekp() does nothing
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>abddec
  </code></pre>
  
  <p>And if I just try to replace the 1st byte of the file, which is 'a' with 'h'</p>
  
  <pre><code>ofstream f("binfile", ios::binary);
  if(f.is_open()){
    char d[]={'c'};
    f.seekp(ios::beg);
    f.write(d, 1);
    f.close();
  }
  //file is erased
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>h
  </code></pre>
  
  <p>What do I do? Is it even possible for the OS to allow a program to edit a file at any point own its own?</p>