-1

I'd like to assign a file path to the program from the terminal,

inside my program the code is like:

#include<iostream>

int main{

fstream file;
file.open("path",ios::in);
...

and I want to use

./myprogram /filepath

in the terminal to let my program receive the path, how can I achieve it?

wasababv
  • 3
  • 1

2 Answers2

2

Your main function declaration should look like this:

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

The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.

The array of character pointers is the listing of all the arguments.

I'd suggest using Boost.Program_options to parse arguments.

Andrew Komiagin
  • 6,446
  • 1
  • 13
  • 23
2

You can use command line arguments. But your main should look like as below. Where argc shows the argument count (including the executable itself) and argv shows the arguments (including the name of the executable itself). So argc = 1, argv = {"myProgram"} by default. (if your output file is "myProgram")

int main (int argc, char* argv[])
{
    fstream file;
    if (argc == 2){
        file.open(argv[1],ios::in);
    }else{
        // handle the error
    }
}

When you run the program :

./myProgram "/filepath"

But make sure to check argc, before using argv[1], to avoid segmentation faults, when there are no additional arguments given.

Praneeth Peiris
  • 2,008
  • 20
  • 40