C++ program append the two text files

By | June 18, 2011

Three file objects are created using the fstream class one for first, second for second file and third for the appended file. The first two files are opened in the input mode and third in the append mode. The first file is opened and checked for error condition if the file exist its contents are written to the third file else the program is aborted with a message on the screen. This process is repeated for the second file also .If the two files exist ,the first file contents are written first and second file contents are written to the third file by appending to its present contents.

#include<iostream.h>
            #include<conio.h>
#include<fstream.h>
#include<process.h>
void main()
{
		fstream file1, file2,file3;
		char ch;
		file1.open("file1.txt",ios :: out);
		file2.open("file2.txt",ios :: out);
		cout << "n Enter data in file 1 n";
		cin.get(ch);
		while(ch != 'n')
		{
			  file1.put(ch);
	 		 cin.get(ch);
		}
		cout << "n Enter data in file 2 n";
		cin.get(ch);
		while(ch != 'n')
		{
			  file2.put(ch);
			  cin.get(ch);
		}
		file1.close();	file2.close();

		file1.open("file1.txt",ios :: in);
		file2.open("file2.txt",ios :: in);
		file3.open("file3.txt",ios :: out | ios :: trunc | ios :: app);
		if(!file1)
		{
			 cout << "n First file not found ";
			 getch();
			 exit(0);
		}
		while(file1)
		{
			 file1.get(ch);
			 file3.put(ch);
		}
		if(!file2)
		{
			 cout << "n Second file not found ";
	 		getch();
			 exit(0);
		}
		while(file2)
		{
			 file2.get(ch);
			 file3.put(ch);
		}
		file1.close();
		file2.close();
		file3.close();
		cout << "nt Appended file contents n";
		file3.open("file3.txt",ios :: in);
		while(file3)
		{
			 file3.get(ch);
			 cout.put(ch);
		}
		getch();
}

Output :

Enter data in file 1
I am coder
Enter data in file 2
I am an student.
Appended file contents
I am coder. I am an student.

Leave a Reply

Your email address will not be published. Required fields are marked *