in reply to Merging of files with some edit.

I would look at the problem differently. Consider the following pseudo-code.
Open output file for update. for each input file open current input file for input read header if (first input) {ouput header} read body output body close input file close output file

You existing code already has nearly all the details. I think you can reorganize it yourself.

Bill