title: How do I fix this output of a simple file read/write program in C?
body: <p>I am writing a very simple file read/write program in C. When I try to test the code, the output is not what I expect. Here is my code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  void hwrite(FILE *fp, int count, char *str) {
          fprintf(fp, "%d ""%s", count, str);
  }
  
  void hread(FILE *fp) {
          if(fp != NULL) {
                  char line [128];
                  while(fgets(line, sizeof line, fp) != NULL) {
                          fputs(line, stdout);
                  }
                  fclose(fp);
          }
          else {
                  perror("xxx.txt");
          }
  }
  
  int main(void) {
          int count = 1;
          char *str = "test text\n";
          FILE *fp;
  
          fp = fopen("xxx.txt", "a");
          int i;
          for (i = 0; i &lt; 3; i++) {
                  hwrite(fp, count, str);
                  count = count+1;
          }
          fp = fopen("xxx.txt", "r");
          hread(fp);
          return 0;
  }
  </code></pre>
  
  <p>The program compiles without issue. I then execute the a.out command once and there is no output. I do it a second time, and there is an output but it is not complete. Here:</p>
  
  <pre><code>[xxxxx xxx]&gt; a.out
  [xxxxx xxx]&gt; a.out
  1 test text
  2 test text
  3 test text
  </code></pre>
  
  <p>Then I open the file to find this:</p>
  
  <pre><code>1 test text
  2 test text
  3 test text
  1 test text
  2 test text
  3 test text
  </code></pre>
  
  <p>Why is it not showing that in the output? Thanks for your time.</p>