Make your own free website on Tripod.com

Lesson 14: Accepting command line arguments

Prev || Home || Next

bar.gif (11170 bytes)

            In C++ it is possible to accept command line arguments. To do so, you must first understand the full definition of int main(). It actually accepts two arguments, one is number of command line arguments, the other is a listing of the command line arguments.

It looks like this:

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

The interger, argc is the ARGument Count (hence argc). It is the number of arguments passed into the program from the command line, including the path to and name of the program.

The array of character pointers is the listing of all the arguments. argv[0] is entire path to the program including its name. After that, every element number less than argc are command line arguments. You can use each argv element just like a string, or use argv as a two dimensional array.

How could this be used? Almost any program that wants it parameters to be set when it is executed would use this. One common use is to write a function that takes the name of a file and outputs the entire text of it onto the screen.

#include <fstream.h> //Needed to manipulate files
#include <iostream.h>
#include <io.h>

int main(int argc, char * argv[])
{
if(argc!=2)
{
cout<<"Sorry, invalid input";
return 0;
}
if(access(argv[1], 00)) //access returns 0 if the file can be accessed
{        //under the specified method (00 is passed in
cout<<"File does not exist"; //because it checks file existence
return 0;
}
ifstream the_file; //ifstream is used for file input
the_file.open(argv[1]); //argv[1] is the second argument passed in
                        //presumable the file name
char x;
the_file.get(x);
while(x!=EOF) //EOF is defined as the end of the file
{
cout<<x;
the_file.get(x);//Notice we always let the loop check x for the end of
} //file to avoid bad output when it is reached
the_file.close(); //Always clean up
}


This program is fairly simle. It first checks to ensure the user added the second argument, theoretically a file name. It checks this, using the access function, which accepts a file name and an access type, with 00 being a check for existence. This is not an standard C++ function. It may not work on your compiler<Then it creates an instance of the file input class,and it opens the second argument passed into main. If you have not seen get before, it is a standard function used in input and output that is used to input a single character into the character passed to it, or by returning the character. EOF is simply the end of file marker, and x is checked to make sure that the next output is not bad.

bar.gif (11170 bytes)

Prev || Home || Next