memes memes - 17 days ago 5
C++ Question

How would I go about merging two text files into a new text file?

I have two text files. First one looks like this.

00000000000000000000000000000000





11100000000000000000000000000000
00010000000000000000000000000000
10100000000000000000000000000000
10100000000000000000000000000000


(the empty spaces in this file are a ' ' space character)

and the other one looks like this

11100000000000000000000000000000
00010000000000000000000000000000
10100000000000000000000000000000
10100000000000000000000000000000
00010000000000000000000000000000


i'd like to insert or replace the empty lines in the first text file with the second text file

Answer

The algorithm is pretty straightforward - it follows the general approach to two-way merging that you see in all algorithms:

  • Open both input files, and the output file, as streams
  • Read lines from the first file one-by-one
  • If the line that you read is non-empty, copy it into the output
  • Otherwise, read the next line from the second file, and copy it into the output
  • Once the first file is exhausted, copy the rest of the second file into the output.
Comments