Lesson 14: Accepting command line arguments 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 //Needed to manipulate files #include #include //Used to check file existence int main(int argc, char * argv[]) { if(argc!=2) { cout<<"Correct input is: filename"; return 0; } if(access(argv[1], 00)) //access returns 0 if the file can be accessed { //under the specified method (00) 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 //presumably the file name char x; the_file.get(x); while(x!=EOF) //EOF is defined as the end of the file { cout<
Hosted by www.Geocities.ws

1