3

How can I read a filename from the command line and utilize it in my C++ code file?

ex: ./cppfile inputFilename outputFilename

Any help is greatly appreciated!

Kevin
  • 16,549
  • 8
  • 60
  • 74
Lady_ari
  • 433
  • 3
  • 8
  • 19
  • 4
    Exact duplicate of http://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line – N_A Oct 04 '11 at 16:59
  • Possible duplicate of [Pass arguments into C program from command line](https://stackoverflow.com/questions/498320/pass-arguments-into-c-program-from-command-line) – Macmade Sep 27 '19 at 11:23

1 Answers1

9
int main(int argc, char** argv) {
    string inFile = "";
    string outFile = "";
    if( argc == 3 ) {
      inFile = argv[1];
      outFile = argv[2];
    }
    else {
      cout << "Usage: ./cppfile InputFile OutputFile\n";
      return 1;
    }
    ...
}
Chriszuma
  • 4,464
  • 22
  • 19
  • 1
    Note that `argv[0]` is the program name; you probably need to check for `argc == 3` and use `argv[1]` and `argv[2]`. – Jonathan Leffler Oct 04 '11 at 16:51
  • Thanks. That helped a lot. Now when I'm using the filenames, can I do something like this: `ifstream inFile; inFile.open(argv[1]);` ? – Lady_ari Oct 04 '11 at 16:52
  • 1
    You also need to include `iostream`, `string` and need to qualify with `std`. – pmr Oct 04 '11 at 17:02
  • 1
    You could turn it around and issue the error `if (argc != 3)`, and then initialise the strings directly: `std::string inFile(argv[1]);`, etc. – Kerrek SB Oct 04 '11 at 17:05