title: Why can't I copy executables like this?
body: <p>Using C++'s <code>&lt;fstream&gt;</code>, it's pretty easy to copy a text file:</p>
  
  <pre><code>#include &lt;fstream&gt;
  
  int main() {
      std::ifstream file("file.txt");
      std::ofstream new_file("new_file.txt");
  
      std::string contents;
      // Store file contents in string:
      std::getline(file, contents);
      new_file &lt;&lt; contents; // Write contents to file
  
      return 0;
  }
  </code></pre>
  
  <p>But when you do the same for an executable file, the output executable doesn't actually work. Maybe std::string doesn't support the encoding?</p>
  
  <p>I was hoping that I could do something like the following, but the file object is a pointer and I'm not able to dereference it (running the following code creates new_file.exe which actually just contains the memory address of something):</p>
  
  <pre><code>std::ifstream file("file.exe");
  std::ofstream new_file("new_file.exe");
  
  new_file &lt;&lt; file;
  </code></pre>
  
  <p>I would like to know how to do this because I think it would be essential in a LAN file-sharing application. I'm sure there are higher level APIs for sending files with sockets, but I want to know how such APIs actually work.</p>
  
  <p>Can I extract, store, and write a file bit-by-bit, so there's no discrepancy between the input and output file? Thanks for your help, it's much appreciated.</p>