title: Overwriting text file in C
body: <p>I would like to start off with this is my first post and I am not doing this as a homework assignment, but rather to just introduce myself to writing in C.</p>
  
  <p>I'm trying to constantly overwrite the file with my for loop, however halfway through the numbers start to go crazy.</p>
  
  <p>Here is the output:</p>
  
  <p>y =  19530</p>
  
  <p>y =  3906</p>
  
  <p>y =  78119530</p>
  
  <p>y =  15623906</p>
  
  <p>y =  -1054493078</p>
  
  <p>Can anyone please provide an explanation as to why in the 3rd iteration of the loop, it jumps to 78119530?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  
  int main(int argc, char *argv[]){
  int x = 19530;
  int y;
  FILE *buff;
  buff = fopen("BUFF.txt","w+");
  
  for(int i = 1; i &lt;= 5; i++){
      fprintf(buff, "%d", x);
      rewind(buff);
      fscanf(buff, "%d", &amp;y);
      printf("y =  %d\n", y);
      y = y/5;
      fclose(fopen("BUFF.txt", "w+"));
      fprintf(buff, "%d", y);
  
      }
  
   return 0;
  }
  </code></pre>