Cit5
Cit5

Reputation: 440

Open file based on user input

I want to get the input file name in advance, when my program is called, not have my program ask the user for the filename.

I've seen many examples where the program will ask the user for input like:

int main()
{
    cout << "Enter file name: ";
    cin.get();
    //run program
    return 0;
}

However, there are not many examples shown where the input is stated in the command line when the program is called:

int main(int argv, char* argc[])
{
    ifstream inputfile;
    inputfile.open(argc);
    //run program
    return 0;
}

In other words, the user would type something like this on the terminal:

$./program example.txt

Sorry if my question is like an ELI5 submission.

I think you guys might get the gist of what I am trying to do.

Upvotes: 0

Views: 178

Answers (2)

R Sahu
R Sahu

Reputation: 206567

You need to use:

inputfile.open(argv[1]);

However, I suggest adding checks to the program.

int main(int argc, char* argv[]){
    if ( argc < 2 )
    {
       cerr << "Not enough arguments.\n";
       return EXIT_FAILURE;
    }

    // There is an argument. Use it.
    ifstream inputfile;
    inputfile.open(argv[1]);

    //run program
    return 0;
}

Upvotes: 0

Ahmed Akhtar
Ahmed Akhtar

Reputation: 1463

Use:

int main(int argc, char* argv[])
{
 ifstream inputfile;
 if(argc == 2)
  inputfile.open(argv[1]);
 else
  cout<<"Please nenter filename as command line argument!\n";
 //run program
 return 0;
}

Here, argc and argv are called command line arguments.

The value of argc is equal to the number of command line arguments, which includes the filename of the executable file itself.

argv is an array of strings passed as command line arguments, where the name of the executable file is at argv[0] and the rest of the arguments follow that.

Upvotes: 2

Related Questions