title: The best way to save data from std::istream to file
body: <p>I have some data in <code>std::istream</code> and I need to save it to the disk. Here is my draft:</p>
  
  <pre><code>    std::istream&amp; i_stream = ReceiveBytes();
  
      FILE* pFile;
      pFile = fopen("C:\\my_file.exe", "wb");
      char buffer[1024] = {0x0};
      i_stream.read(buffer, 1024);
      std::streamsize n = i_stream.gcount();
  
      while (n &gt; 0)
      {  
          if (i_stream)
          {
              fwrite(buffer, sizeof(char), sizeof(buffer), pFile);
              i_stream.read(buffer, 1024);
              n = i_stream.gcount();
          }
          else n = 0;
      }
  
      fclose(pFile);
  </code></pre>
  
  <p>For some reason I don't save all the data from <code>i_stream</code>, I lose about 50 bytes in the end of the <code>i_stream</code>. What did I do wrong in the code? Is there any better solutions to save data from <code>std::istream</code> to a file ?</p>