title: ReadFile() in Windows
body: <p>I am trying to read from a file using the Windows function <code>ReadFile()</code>, but when I print the message it prints too many characters. </p>
  
  <p>It doesn't matter if I read from an ANSII file or UNICODE file, I don't get the right characters.</p>
  
  <p>Text in file is : "This is a text file".</p>
  
  <p>Screen shot for the ANSII file:
  <a href="https://i.stack.imgur.com/46aho.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/46aho.png" alt="screen shot for ANSII file ReadFile()"></a></p>
  
  <p>Screen shot for the UNICODE file:
  <a href="https://i.stack.imgur.com/89Chm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89Chm.png" alt="screen shot for the UNICODE file ReadFile()"></a></p>
  
  <p>What Am I doing wrong?</p>
  
  <pre><code>#define BUFSIZE 4000
  
  
  int _tmain(int argc, TCHAR *argv[])
  {
      HANDLE  hIn;
      TCHAR buffer[BUFSIZE];
      DWORD nIn = 0;
  
      //create file
      hIn = CreateFile(argv[1],
          GENERIC_READ,
          FILE_SHARE_READ,
          NULL,
          OPEN_EXISTING,
          FILE_ATTRIBUTE_NORMAL,
          NULL);
      //check the handle
      if (hIn == INVALID_HANDLE_VALUE)
      {
          printf("\nOpen file error\n");
      }
      //read from file
      if (FALSE == ReadFile(hIn, buffer, BUFSIZE - 1, &amp;nIn, NULL))
      {
          printf("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError());
          CloseHandle(hIn);
          return 0;
      }
  
      if (nIn &gt; 0 &amp;&amp; nIn &lt;= BUFSIZE - 1)
      {
          buffer[nIn] = TEXT('\0'); // NULL character
          _tprintf(TEXT("Data read from %s (%d bytes): \n"), argv[1], nIn);
      }
      else if (nIn == 0)
      {
          _tprintf(TEXT("No data read from file %s\n"), argv[1]);
      }
      else
      {
          printf("\n ** Unexpected value for nIn ** \n");
      }
      printf("1:%s\n", buffer);
      _tprintf(TEXT("\n2:%s"), buffer);
  
      return 0;
  }
  </code></pre>