codescracker


c++

C++ Program to Copy Files



« Previous Program Next Program »


Copy Files in C++

To copy the content of one file to the other file in C++ programming, you have to first ask to the user to enter the source file to open the source file and then ask to enter the target file to open the target file and start reading the source file's content character by character and place or write the content of the source file to the target file character by character at the time of reading as shown here in the following program.

C++ Programming Code to Copy Files

Following C++ program ask to the user to enter the two file name. First file name is source file (the content of this file is going to copy to the target file) and the second name is target file (the content of the source file is copied to this target file). After entering the two file name, the below program start copying the content of the source file to the target file. After copying it will message file copied successfully :

/* C++ Program - Copy Files */
		
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
	clrscr();
	ifstream fs;
	ofstream ft;
	char ch, fname1[20], fname2[20];
	cout<<"Enter source file name with extension (like files.txt) : ";
	gets(fname1);
	fs.open(fname1);
	if(!fs)
	{
		cout<<"Error in opening source file..!!";
		getch();
		exit(1);
	}
	cout<<"Enter target file name with extension (like filet.txt) : ";
	gets(fname2);
	ft.open(fname2);
	if(!ft)
	{
		cout<<"Error in opening target file..!!";
		fs.close();
		getch();
		exit(2);
	}
	while(fs.eof()==0)
	{
		fs>>ch;
		ft<<ch;
	}
	cout<<"File copied successfully..!!";
	fs.close();
	ft.close();
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program to copy file

After running the above C++ program, your target file will contain the source file's content

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test