// Merge two files into a third file.
// By DreamVB 00:30 21/10/2016

#include <iostream>

using namespace std;
using std::cout;
using std::endl;

int main(int argc, char *argv[]){
	FILE *f1 = NULL;
	FILE *f2 = NULL;
	FILE *f3 = NULL;
	char c = '\0';

	if (argc != 4){
		cout << "Merge two files into a third file." << endl;
		cout << "Usage: " << argv[0] << " <source1><source2><destination>" << endl << endl;
		exit(1);
	}

	else{
		//Open file 1
		f1 = fopen(argv[1], "rb");
		
		//Check file 1 was opened.
		if (!f1){
			cout << "Cannot open first file." << endl;
			exit(1);
		}

		//Open file 2
		f2 = fopen(argv[2], "rb");

		//Check file 2 was opened.
		if (!f2){
			cout << "cannot open second file." << endl;
			fclose(f1);
			exit(1);
		}

		//Open file 3
		f3 = fopen(argv[3], "wb");
		//Check file 3 was opened.

		if (!f3){
			fclose(f2);
			fclose(f1);
			exit(1);
		}

		//Merge the two files into the thid file.

		//Get file 1 contents and write to file 3
		while (!feof(f1)){
			c = fgetc(f1);
			if (feof(f1)){
				break;
			}
			//Put char to file 3
			fputc(c, f3);
		}
		//Get file 2 contents and write to file 3
		while (!feof(f2)){
			c = fgetc(f2);
			if (feof(f2)){
				break;
			}
			//Put char to file 3
			fputc(c, f3);
		}

		//Close files
		fclose(f3);
		fclose(f2);
		fclose(f1);
	}
	return 0;
}