title: Concatenate two huge files in C++
body: <p>I have two std::ofstream text files of a hundred plus megs each and I want to concatenate them. Using fstreams to store the data to create a single file usually ends up with an out of memory error because the size is too big.</p>
  
  <p>Is there any way of merging them faster than O(n)?</p>
  
  <p>File 1 (160MB):</p>
  
  <pre><code>0 1 3 5
  7 9 11 13
  ...
  ...
  9187653 9187655 9187657 9187659 
  </code></pre>
  
  <p>File 2 (120MB):</p>
  
  <pre><code>a b c d e f g h i j
  a b c d e f g h j i
  a b c d e f g i h j
  a b c d e f g i j h
  ...
  ...
  j i h g f e d c b a
  </code></pre>
  
  <p>Merged (380MB):</p>
  
  <pre><code>0 1 3 5
  7 9 11 13
  ...
  ...
  9187653 9187655 9187657 9187659 
  a b c d e f g h i j
  a b c d e f g h j i
  a b c d e f g i h j
  a b c d e f g i j h
  ...
  ...
  j i h g f e d c b a
  </code></pre>
  
  <p>File generation:</p>
  
  <pre><code>std::ofstream a_file ( "file1.txt" );
  std::ofstream b_file ( "file2.txt" );
  
      while(//whatever){
            a_file &lt;&lt; num &lt;&lt; endl;
      }
  
      while(//whatever){
            b_file &lt;&lt; character &lt;&lt; endl;
      }
  
      // merge them here, doesn't matter if output is one of them or a new file
      a_file.close();
      b_file.close();
  </code></pre>