title: How to read numbers from file and save the mean of them into the same file?
body: <p>I have a txt file with two columns:</p>
  
  <pre><code>1 2
  3 4
  5 6
  7 8
  </code></pre>
  
  <p>I would like to read those numbers, calculate the mean and save the result into the third column in the same file. I opened my file for update <code>"r+"</code> but it seem not to work. Reading is fine but when I add the third column something wrong is happening with the file ... It seems that its being rewritten, theres no original content in it when I call my <code>fun</code> - after the first loop instruction. Any ideas? </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void fun(const char *filename)
  {
      double num1 = 0, num2 = 0, num3 = 0;
      FILE *f;
      if((f = fopen(filename, "r+")) == NULL)
      {
          exit(-1);
      }
  
      while(fscanf(f, "%lf %lf", &amp;num1, &amp;num2) != EOF)
      {
          //printf("num1 = %.2f, num2 = %.2f\n", num1, num2);
          num3 = num1 + num2;
          fprintf(f, "%lf %lf %lf\n", num1, num2, num3/2.0);
      }
  
      fclose(f);
  }
  
  int main(int argc, char **argv)
  {
      fun("numbers.txt");
  
      return 0;
  }
  </code></pre>
  
  <p>When my program ends execution, I would like to have in my txt file 3 columns:</p>
  
  <pre><code>1 2 1.5
  3 4 3.5
  5 6 5.5
  7 8 7.5
  </code></pre>
  
  <p><strong>Tried also this but my program just hangs out:</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  void fun(const char *filename)
  {
      double num1 = 0, num2 = 0, num3 = 0;\
  
      FILE *f;
      if((f = fopen(filename, "r+")) == NULL)
      {
          exit(-1);
      }
  
      int write_at = 0, read_at = 0;
  
      while(fscanf(f, "%lf %lf", &amp;num1, &amp;num2) != EOF)
      {
          read_at = ftell(f);
          fseek(f, write_at, SEEK_SET);
          num3 = num1 + num2;
          fprintf(f, "%lf %lf %lf\n", num1, num2, num3/2.0);
          write_at = ftell(f);
          fseek(f, read_at, SEEK_SET);
      }
  
      fclose(f);
  }
  
  int main(int argc, char **argv)
  {
      fun("numbers.txt");
      return 0;
   }
  </code></pre>