Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, how to provide the input filename from the command line, without hardcoding it in the program?

Tags:

c++

filenames

This is the continuation of my previous question, In C++, how to read the contents of a text file, and put it in another text file?

In that, I was able to able to open an input file input.txt and read it contents successfully, but now i don't want to hardcode or give the input filename beforehand,

ifstream myfile ("input.txt");
if (myfile.is_open())

but i want to give the input file name later after compiling the program and generating an executable file named testin the command line, as shown below

./test input.txt

Any suggestions on how to do this ?

like image 852
user2917559 Avatar asked Mar 20 '23 14:03

user2917559


2 Answers

You can access the command line arguments passed to your program in the main function:

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

argc is the number of arguments passed to your program and argv contains pointers to C-strings holding the arguments passed to your program. So using this array you can access the arguments passed to your program.

But you have to pay attention: the program itself is always passed to the program as first argument. So argc is always at least one and argv[0] contains the program name.

If you want to access the input.txt from your post you could write:

int main(int argc, char *argv[]) {
   if (argc > 1) {
      // This will print the first argument passed to your program
      std::cout << argv[1] << std::endl;
   }
}
like image 162
sleepy1771 Avatar answered Apr 06 '23 20:04

sleepy1771


Just to addon to all the answers - You can use 'standard input and output' of C/C++ like printf() & scanf()

$ ./a.out < input.file // input file
$ ./a.out > output.file // output file
$ ./a.out < input.file > output.file // merging above two commands.

For more info: REFER THIS

And ofcourse, clean way is to use argc/argv as answered by fellow gentlemen.

like image 37
iankits Avatar answered Apr 06 '23 21:04

iankits