Archive

Archive for January 31, 2010

C++ Program to implement File Handling with Command Line Arguments – Q31

January 31, 2010 Leave a comment

Q31. Program to implement File Handling with Command Line Arguments:

Copy the contents of an existing file to a new file the names of which are taken as command line arguments. The program should handle errors if the given first file name does not already exist.

… from College notes (BCA/MCA assignments):

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

void main(int argc, char *argv[]){
	char src[12], dest[12];
	char buff[1000];
	int len;
	clrscr();

	if(argc > 3){
		cout<<"\n Illegal Number of Arguments."<<endl;
		exit(1);
		}
	else if(argc == 2){
		cout<<"\n Enter the Destination File."<<endl;
		cin>>dest;
		}
	else if(argc == 1){
		cout<<"\n Enter Source and Destination File."<<endl;
		cin>>src;
		cin>>dest;
		}
	else{
		strcpy(src, argv[1]);
		strcpy(dest, argv[2]);
		}

	ifstream fin;
	fin.open(src, ios::in);

	if(!fin){
		cerr<<"\n File Does not Exist.";
		getch();
		exit(1);
		}
	fin.read((char*)&buff, sizeof(buff));
	fin.close();

	len = strlen(buff) - 1;

	ofstream fout;
	fout.open(dest, ios::out);
	fout.write((char*)&buff, len);
	fout.close();

	cout<<"\n File copied Successfully.";

	getch();
	}

 

Output:

C:\TC\MANOJ>31_FH.exe man.txt abc.txt

File Copied Successfully.


Advertisement