title: How to read and overwrite text file in C?
body: <p>I have a text file text.txt that reads (for simplicity purposes)</p>
  
  <pre><code>this is line one
  this is line two
  this is line three
  </code></pre>
  
  <p>Again for simplicity's sake, I am just trying to set the first character in each line to 'x', so my desired result would be</p>
  
  <pre><code>xhis is line one
  xhis is line two
  xhis is line three
  </code></pre>
  
  <p>So I am opening the text.txt file and trying to overwrite each line with the desired output to the same text file. In the while loop, I set the first character in each line to 'x'. I also set the variable "line" equal to one, because if its on the first line, I want to rewind to the beginning of the file in order to overwrite at the start instead of at the end of the file. Line is then incremented so it will skip the rewind for the next iteration, and should continue to overwrite the 2nd and 3rd lines. It works perfectly for the first line. </p>
  
  <p>Anybody have any solutions? BTW, I have researched this extensively both on stackoverflow and other sites, and no luck. Here's my code and my output is also below:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #define MAX 500
  
  int main() {
      char *buffer = malloc(sizeof(char) * MAX);
      FILE *fp = fopen("text.txt", "r+");
      int line = 1;
      while (fgets(buffer, 500, fp) != NULL) {
              buffer[0] = 'x';
              if (line == 1) {
                      rewind(fp);
                      fprintf(fp, "%s", buffer);
              }
              else {
                      fprintf(fp, "%s", buffer);
              }
              line++;
      }
      free(buffer);
      fclose(fp);
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>xhis is line one
  this is line two
  xhis is line two
  e
  x
  </code></pre>