title: How to overwrite a file in C?
body: <p>I am trying to overwrite the contents of a FILE in C. Currently I have:</p>
  
  <pre><code>FILE* file  = fopen("filename.txt",  "r+");
  fprintf(file, "%d", 1); // regardless of what's in the file, i want to clear it and put 1 in there
  ...
  // legacy code somewhere else in the code base. can't change.
  rewind(file);
  fprintf(file, "%d", 2);
  fflush(file);
  </code></pre>
  
  <p>However, this will not work properly. The result will be:</p>
  
  <p>1, 21</p>
  
  <p>Each subsequent number will be written to the beginning of the 1. For example:</p>
  
  <p>1, 21, 31, 41, ...</p>
  
  <p>I would like to know if there is a way to always overwrite what's in the file so the following is produced:</p>
  
  <p>1, 2, 3, 4, ...</p>
  
  <p>Any assistance would be appreciated.</p>
  
  <p>Thank you.</p>
  
  <p>EDIT:</p>
  
  <p>I have changed the code to:</p>
  
  <pre><code>FILE* file  = fopen("filename.txt",  "w+");
  </code></pre>
  
  <p>The problem still persists.</p>