Skip to main content

C++ 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.



#include
#include
#include
#include
#include
 
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."<
        exit(1);
        }
    else if(argc == 2){
        cout<<"\n Enter the Destination File."<
        cin>>dest;
        }
    else if(argc == 1){
        cout<<"\n Enter Source and Destination File."<
        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();
    }

Comments