Download Quick Currency Converter


Copy File C/C++

Description:This project is a simple file copier. It can copy any kind of file(documents, media files, .exe file, everything). This program can only be called from command prompt where you need to provide source and destination file path as additional arguments.(You can easily modify it to take arguments during execution of the program). Note that this is not the best method to copy a file. It might be slower and inefficient. However, it demonstrates basic operation using file handling, such as reading and writing a file.

Difficulty: Medium

Language: C++

Compiler/IDE: Visual Studio, dev C++ (others will work as well)





View Source

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

using namespace std;

bool copyFile(char *src, char *des);

int main(int argc, char *argv[])
{

	char src[255], des[255];
	if (argc < 2)		
	{
           cout<<"Please enter source and destination file as separate arguments\n";
           cout<< "For example 'src.pdf des.pdf'\n";
           system("pause");
           return 0;

	}
	else
	{
		strcpy(src, argv[1]);
		strcpy(des, argv[2]);
	}


	if (copyFile(src, des))
		cout<<"File copied successfully\n";
	else
		cout<<"File not copied\n";

	getch();
	return 0;


}


bool copyFile(char *src, char *des)
{

	ifstream inpfile(src, ios::binary);

	if (!inpfile.is_open())
		return false;
	
	//check if the destination file already exist; so open it for reading...
	ifstream outcheck(des, ios::binary);
	if (outcheck)
	{
		cout<<"Destination file already exist\n";
		inpfile.close();
		outcheck.close();
		return false;
	}
	else
		outcheck.close();

	ofstream outfile(des, ios::binary);
		

	if ( !outfile.is_open())
	{
		inpfile.close();
		return false;
	}

	cout<<"Please Wait...\n";

	string line;
	while(!inpfile.eof())
	{
		getline(inpfile, line);
		outfile<< line;
		outfile<< '\n';
	}

	inpfile.close();
	outfile.close();


	return true;
}       


Notes:The project takes the source and destination file arguments and call the function "copyFile". If the destination file already exists, it throws an error and exits, otherwise the program takes 1 line from input file (delimited by \n) and copies it to the output file. It keeps on copying until end of input file is reached.

A sample run of the program from command prompt(assumming .exe name is copy.exe) is :

"d:\programs directory\copy.exe" "d:src.jpg" "e:\des.jpg"