C++ program to copy the contents of a text file to another

By | June 18, 2011

Two file objects are created using the fstream class for the two files, one for source file and another destination file. The first file is opened and its contents are copied to the second file using get ( ) and put ( ) function. Each time the source file is opened error checking is done to ensure that the file is existing else the program is aborted with a message.

If the contents are successfully copied, the destination file contents are displayed on the screen.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<process.h>

void main()
{
		fstream file1, file2;
		char ch;
		clrscr();
		file1.open("file1.txt",ios :: out);
		cout << "nt Press 'enter key' to quit nn";
		cout << "n Enter the data n";
		cin.get(ch);
		while(ch != 'n')
		{
	   		 file1.put(ch);
	    		cin.get(ch);
		}
		file1.close();
		file1.open("file1.txt",ios :: in);
		if(!file1)
		{
			 cout<< "n File1 not found !! n";
			 getch();
			 exit(0);		// aborting…
		}
		cout << "n First file contents n";
		while(file1)
		{
			 file1.get(ch);
			 cout.put(ch);
		}
		file1.seekg(0);		      	    /* copying process..... */
		file2.open("file2.txt",ios :: out );
		cout << "nn First file contents copied to second file... n";
		while(file1)
		{
			 file1.get(ch);
			 file2.put(ch);
		}
		file1.seekg(0);
		file2.close();
		file2.open("file1.txt",ios :: in);
		if(!file1)
		{
			 cout<< "n File1 not found !! n";
			 getch();
			 exit(0); 		// aborting…
		}
		cout << "n Second file contents n";
		while(file2)
		{
			 file2.get(ch);
			 cout.put(ch);
		}
		file2.close();
		getch();
}

The output is like this

Press ‘enter key’ to quit
Enter the data
I am an Indian
First file contents
I am an Indian
First file contents copied to second file…
Second file contents
I am an Indian

Leave a Reply

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