title: Unable to read complete data from named pipe
body: <p>I have a client and a server communicating using a named pipe. </p>
  
  <p>I'm trying to pass the address stored by an LPCWSTR variable from the client to the server.</p>
  
  <p>To do this, I first write the address onto a wchar_t buffer, then I send the server the size of that buffer (as a DWORD), so now the server knows how many bytes it has to read. I managed to send the buffer size successfully, I'm unable to send the complete string though.</p>
  
  <p>Even though the server says it has read the required number of bytes, the buffer on the server side doesn't have the entire string.</p>
  
  <p>Client: </p>
  
  <pre><code>wchar_t msgBuffer[1024];
  LPCWSTR lpName = L"NameString";
  
  _swprintf(msgBuffer, _T("%p\0"), lpName);       //Write data to the buffer
  
  DWORD nBytesToWrite = wcslen(msgBuffer);        //Number of bytes to be written
  
  bWriteFile = WriteFile(                         //Send the buffer size
      hCreateFile,
      &amp;nBytesToWrite,
      (DWORD)sizeof(nBytesToWrite),
      &amp;dwNoBytesWritten,
      NULL
  );
  
  bWriteFile = WriteFile(                         //Send the data
      hCreateFile,
      msgBuffer,
      (DWORD)wcslen(msgBuffer),
      &amp;dwNoBytesWritten,
      NULL
  );
  </code></pre>
  
  <p>Server: </p>
  
  <pre><code>DWORD dwBytesToRead = 0;
  
  bReadFile = ReadFile(                           //Read the size of the next message
      hCreateNamedPipe,
      &amp;dwBytesToRead,
      sizeof(DWORD),
      &amp;dwNoBytesRead,
      NULL);
  
  std::cout &lt;&lt; "\nBytes to be read: " &lt;&lt; dwBytesToRead;
  
  wchar_t msg[] = L"";
  
  bReadFile = ReadFile(                           //Read the data
      hCreateNamedPipe,
      &amp;msg,
      dwBytesToRead,
      &amp;dwNoBytesRead,
      NULL);
  
  std::cout &lt;&lt; "\nBytes Read: " &lt;&lt; dwNoBytesRead;// &lt;&lt; '\n' &lt;&lt; msg;
  wprintf(L"\nMessage: %s\nSize: %zu", msg, wcslen(msg));
  </code></pre>
  
  <p>This is what the output on the server side is:</p>
  
  <blockquote>
    <p>Bytes to be read: 9 </p>
    
    <p>Bytes Read: 9</p>
    
    <p>Message: 78E7 </p>
    
    <p>Size: 5</p>
  </blockquote>
  
  <p>The address is <code>78E7325C</code> on the client side, but my server only prints <code>78E7</code></p>
  
  <p>Even though the server says to have read 9 bytes, the size of the resultant wchar_t is just 5, why is this?</p>
  
  <p>EDIT: I've checked the buffer on the client side, it has the correct address stored. And is it okay to be sending the DWORD variable using the address-of (&amp;) operator in WriteFile()?</p>
  
  <p><strong>The Solution</strong></p>
  
  <p>Changed <code>(DWORD)wcslen(nBytesToWrite)</code> to <code>(DWORD)sizeof(nBytesToWrite)</code></p>
  
  <p><code>wcslen</code> gives the number of characters, whereas <code>sizeof</code> gives the number of bytes, and these aren't the same. </p>