title: Reading and writing binary files in C
body: <p>These are 2 separate applications.</p>
  
  <ul>
  <li>In the first one, I tried to store employee details like name, age and salary in the binary file named <code>emp.bin</code>.</li>
  <li>In the second application, I tried to view the contents of the file but in place of the name, only the first character appears.</li>
  </ul>
  
  <p>I tried printing each character separately, and it turns out that there's 3 null characters '\n' after each letter in the name that is why it is not printing after the first character.</p>
  
  <p>"Write" application code:</p>
  
  <pre><code>//Receives records from keyboard and writes them to a file in binary mode
  #include &lt;stdio.h&gt;
  
  int main()
  {
      FILE *fp;
      char another = 'Y';
      struct emp
      {
          char name[40];
          int age;
          float bs;
      };
      struct emp e;
      fp = fopen("emp.bin", "wb");
      if (fp == NULL)
      {
          puts("Cannot open the file.");
          return 1;
      }
      while(another == 'Y')
      {
          printf("Enter the employee name, age and salary: ");
          scanf("%S %d %f", e.name, &amp;e.age, &amp;e.bs);
          while(getchar() != '\n');
          fwrite(&amp;e, sizeof(e), 1, fp);
          printf("Add another record? (Y/N)");
  
          another = getchar();
      }
      fclose(fp);
      return 0;
  }
  </code></pre>
  
  <p>"Read" application code:</p>
  
  <pre><code>//Read records from binary file and displays them on VDU
  #include &lt;stdio.h&gt;
  #include &lt;ctype.h&gt;
  
  int main()
  {
      FILE *fp;
      struct emp
      {
          char name[40];
          int age;
          float bs;
      } e;
      fp = fopen("emp.bin", "rb");
      if (fp == NULL)
      {
          puts("Cannot open the file.");
          return 1;
      }
      while (fread(&amp;e, sizeof(e), 1, fp) == 1)
      {
          printf("\n%s \t %d \t $%.2f\n", e.name, e.age, e.bs);
      }
      fclose(fp);
  }
  </code></pre>
  
  <p>Here's the input and output:</p>
  
  <p><img src="https://i.stack.imgur.com/qSt47.png" alt="enter image description here">
  <img src="https://i.stack.imgur.com/4JNXt.png" alt="enter image description here"></p>
  
  <p>How can I correct this code to make it print the whole name?</p>