Computer Science Canada

Command Line Arguments

Author:  LearningC++ [ Sun Nov 29, 2009 10:21 pm ]
Post subject:  Command Line Arguments

I'm using a tutorial and I got to command line arguments. I don't get some of the code:

#include <fstream>
#include <iostream>

using namespace std;

int main ( int argc, char *argv[] )
{
if ( argc != 2 ) // argc should be 2 for correct execution
cout<<"usage: "<< argv[0] <<" <filename>\n";
else {
ifstream the_file ( argv[1] );
if ( !the_file.is_open() )
cout<<"Could not open file\n";
else {
char x;
while ( the_file.get ( x ) )
cout<< x;
}
}
}

Why does argc have to be 2 for it to be correct?

What is this program trying to do?

Author:  Tony [ Sun Nov 29, 2009 10:32 pm ]
Post subject:  RE:Command Line Arguments

The correct usage of this program requires the argument counter to be 2: program name + filename. Try running the program to see what it does (or read the source code).

Author:  LearningC++ [ Sun Nov 29, 2009 10:45 pm ]
Post subject:  Re: Command Line Arguments

Running it displays the location of the program.

Author:  Tony [ Sun Nov 29, 2009 10:58 pm ]
Post subject:  RE:Command Line Arguments

as part of the "usage: " message?

Author:  LearningC++ [ Sun Nov 29, 2009 11:25 pm ]
Post subject:  RE:Command Line Arguments

Ya argv[0] is just the filename I guess.

Author:  DtY [ Mon Nov 30, 2009 6:32 pm ]
Post subject:  Re: RE:Command Line Arguments

LearningC++ @ Sun Nov 29, 2009 11:25 pm wrote:
Ya argv[0] is just the filename I guess.
argv[0] is what ever you used to start the program, so if you rub ./program it will show different output than if you ran /full/path/to/program


: