Sumanth_newbie
Sumanth_newbie

Reputation: 13

Problems while parsing command line arguments

Here is my code:

#include <iostream>
#include <fstream>

using namespace std;

int main (int argc, char * argv[])
{
    char * inputFileName = new char ;
    char * outputFileName = new char ;
    *(inputFileName)='\0';
    *(outputFileName)='\0';
    if(argc!=3)
    {
            cout<<"\n\nWRONG SET OF ARGUMENTS!!\n\nSYNTAX:\n"<<endl;
            cout<<"\n./FileCp <SOURCE> <DESTINATION>\n"<<endl;
            return 1;
    }
    strcpy(inputFileName,argv[1]);
    strcpy(outputFileName,argv[2]);

    cout<<"Input File Name = "<<inputFileName<<endl ;
    cout<<"Output File Name = "<<outputFileName<<endl ;
}

This is the command I used:

./FileCp /Users/sumanthdamarla/Downloads/20130530_235557.jpg jkhs.jpg

And here is the output:

Input File Name = /Users/sumanthdajkhs.jpg
Output File Name = jkhs.jpg

The inputFileName is being overridden by outputFileName. How to resolve this?

Upvotes: 0

Views: 258

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

char * inputFileName = new char ;
char * outputFileName = new char ;

These two lines allocate space for exactly one character each.

strcpy(inputFileName,argv[1]);
strcpy(outputFileName,argv[2]);

These two lines, copies at least 2 characters (as otherwise it wouldn't count as an argument - an argument can't be "empty").

I would suggest that you use std::string instead of allocating memory. Then you can just do outFilename = argv[2]; and not have to worry about it's size.

Alternatively, if you are not going to use the name for anything other than keep it in a name that makes more sense than argv[2], then you could just declare const char *outFilename, and set it with outFilename = argv[2]; - but beware that modifying the contents of argv[2] is not recommended, as you don't know what is "behind it".

Upvotes: 3

Related Questions