title: fread() a struct in c
body: <p>For my assignment, I'm required to use fread/fwrite. I wrote</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  struct rec{
      int account;
      char name[100];
      double balance;
  };
  
  int main()
  {
      struct rec rec1;
      int c;
  
      FILE *fptr;
      fptr = fopen("clients.txt", "r");
  
      if (fptr == NULL)
          printf("File could not be opened, exiting program.\n");
      else
      {
          printf("%-10s%-13s%s\n", "Account", "Name", "Balance");
          while (!feof(fptr))
          {
              //fscanf(fptr, "%d%s%lf", &amp;rec.account, rec.name, &amp;rec.balance);
              fread(&amp;rec1, sizeof(rec1),1, fptr);
              printf("%d %s %f\n", rec1.account, rec1.name, rec1.balance);
          }
          fclose(fptr);
      }
      return 0;
  }
  </code></pre>
  
  <p>clients.txt file</p>
  
  <pre>
  100 Jones 564.90
  200 Rita 54.23
  300 Richard -45.00
  </pre>
  
  <p>output</p>
  
  <pre>
  Account   Name         Balance
  540028977 Jones 564.90
  200 Rita 54.23
  300 Richard -45.00╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
  ╠╠ü☻§9x°é -92559631349317831000000000000000000000000000000000000000000000.000000
  
  Press any key to continue . . .
  </pre>
  
  <p>I can do this with fscanf (which Ive commented out), but I'm required to use fread/fwrite.</p>
  
  <ol>
  <li>Why does it start with a massive number for Jone's account? </li>
  <li>Why is there garbage after? Shouldn't feof stop this?</li>
  <li>Are there any drawbacks using this method? or fscanf method?</li>
  </ol>
  
  <p>How can I fix these? 
  Many thanks in advance</p>