title: How do I overwrite a single byte in a binary file using fseek() and fwrite()?
body: <p>I am trying to overwrite a single byte in a binary file. I am using <code>fseek()</code> to set the stream position indicator to the byte that I want to overwrite. Then I am calling to <code>fwrite()</code> with a new byte in that location. Somehow the other bytes in the file are being affected. Heres some code:</p>
  
  <pre><code>bool x = 1;
  bool y = 0;
  bool z = 1;
  
  /* WRITE 101 to file */
  FILE *ff = fopen(file, "wb");
  fwrite(&amp;x, sizeof(x), 1, ff);
  fwrite(&amp;y, sizeof(y), 1, ff);
  fwrite(&amp;z, sizeof(y), 1, ff);
  
  fclose(ff);
  
  bool x_r, y_r, z_r;
  
  /* READ from file */
  ff = fopen(file, "rb");
  fread(&amp;x_r, sizeof(x_r), 1, ff);
  fread(&amp;y_r, sizeof(y_r), 1, ff);
  fread(&amp;z_r, sizeof(z_r), 1, ff);
  
  fclose(ff);
  
  /* PRINT to standard output */
  cout &lt;&lt; x_r &lt;&lt; y_r &lt;&lt; z_r &lt;&lt; endl; // OUTPUT: 101
  
  bool overwrite = 1;
  
  /* OVERWRITE */
  ff = fopen(file, "wb");
  
  fseek(ff, 1, SEEK_SET);
  fwrite(&amp;overwrite, sizeof(overwrite),1 , ff);
  fclose(ff);
  
  
  /* READ from file */
  ff = fopen(file, "rb");
  fread(&amp;x_r, sizeof(x_r), 1, ff);
  fread(&amp;y_r, sizeof(y_r), 1, ff);
  fread(&amp;z_r, sizeof(z_r), 1, ff);
  
  fclose(ff);
  
  /* PRINT to standard output */
  cout &lt;&lt; x_r &lt;&lt; y_r &lt;&lt; z_r &lt;&lt; endl; // OUPUT 011; I was expecting 111 
  </code></pre>
  
  <p>The above code basically writes three bytes of data to a file. 101. Then I use fseek() to set to reposition the stream indicator to point to the second byte. But calling fwrite() to overwrite the second byte from 0 to 1 is changing the first byte as well. The expected output is 111, but I am getting 011.</p>
  
  <p>Any ideas why this is happening? I tried putc as well, but that didn't work out either. Any help would be appreciated.</p>