![]() ![]() | ||||
![]() ![]() |
Lesson 14: Accepting
command line arguments (Printable
Version) #include <fstream.h> //Needed to manipulate files #include <iostream.h> #include <io.h> //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<<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 return 0; }This program is fairly simple. It incorporates the full version of main. Then 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 a 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. Previous: Functions Continued Next: Linked Lists ----- |
| ||
|