/////////////////////////////////////////////////////////////////////// // // args.cpp // // Jeff Ondich and the CS257 class // // Written communally during class (spring 2004) to illustrate // one approach to parsing command-line arguments in C/C++. The // basic approach is: (1) set your default behaviors, (2) scan // through the arguments to set non-default behaviors, and // (3) execute the specified behaviors. // // The program's job, such as it is, is to change its input to // upper case, sending the output to standard out. The input // can come from either a file or standard input, and there are // usage and version flags that override the input->output // and just print suitable messages. // /////////////////////////////////////////////////////////////////////// #include #include using namespace std; void printUsageStatement( const char *progName ); void printVersionStatement( const char *progName ); void capitalize( istream& in ); int main( int argc, char *argv[] ) { // Set default behaviors. char *fileName = NULL; bool printUsage = false; bool printVersion = false; // Parse command line. for( int k=1; k < argc; k++ ) { if( strcmp( argv[k], "-u" ) == 0 ) printUsage = true; else if( strcmp( argv[k], "-v" ) == 0 ) printVersion = true; else if( k < argc - 1 ) { // A file for input can only be the last argument. // Thus, if we find something that isn't a valid // option before the last argument, we have an // invalid command line. printUsage = true; } else // There's a single file specified. { fileName = argv[k]; } } // Print usage and/or version statements, if appropriate. if( printUsage || printVersion ) { if( printVersion ) printVersionStatement( argv[0] ); if( printUsage ) printUsageStatement( argv[0] ); exit( 1 ); } // Copy the input to standard output, converting to // upper case along the way. if( fileName != NULL ) { ifstream fin; fin.open( fileName ); if( !fin.is_open() ) { cerr << "Can't open file " << fileName << endl; exit( 1 ); } capitalize( fin ); } else capitalize( cin ); return 0; } void printUsageStatement( const char *progName ) { cerr << "Usage: " << progName << " [-u] [-v] [file]" << endl; } void printVersionStatement( const char *progName ) { cerr << "Version: " << progName << " -0.1" << endl; } void capitalize( istream& in ) { char ch; while( in.get( ch ) ) { ch = toupper( ch ); cout << ch; } }