// Purpose: copy file // // Command syntax: // $ ./a.out [ size (>= 0) | 'd' (default 20) [ code (>= 0) | 'd' (default 5) [ input-file [ output-file ] ] ] ] // all parameters are optional. Defaults: size=>20, code=>5, input=>cin, output=>cout // // Examples: // $ ./a.out 34 // $ ./a.out 34 0 // $ ./a.out 34 0 in // $ ./a.out 34 0 in out #include // sin/sout #include // convert #include // strcmp #include // errno // convert(...) throws out_of_range or invalid_argument ExceptionDecl( cmd_error ); int main( int argc, char * argv[] ) { enum { DefaultSize = 20, DefaultCode = 5 }; // global defaults // MUST BE INT (NOT UNSIGNED) TO CORRECTLY TEST FOR NEGATIVE VALUES intmax_t size = DefaultSize, code = DefaultCode; // default value ifstream infile = stdin; // default value ofstream outfile = stdout; // default value try { choose ( argc ) { case 4: case 5: try { // open input file first as output creates file open( infile, argv[3] ); } catch( open_failure * ) { // open failed ? sout | "Error! Could not open input file \"" | argv[3] | "\""; throw ExceptionInst( cmd_error ); } // try if ( argc == 5 ) { try { open( outfile, argv[4] ); } catch( open_failure * ) { // open failed ? sout | "Error! Could not open output file \"" | argv[4] | "\""; throw ExceptionInst( cmd_error ); } // try } // if fallthrough; case 3: if ( strcmp( argv[2], "d" ) != 0 ) { // default ? code = convert( argv[2] ); if ( code < 0 ) throw ExceptionInst( cmd_error ); // invalid ? } // if fallthrough; case 2: if ( strcmp( argv[1], "d" ) != 0 ) { // default ? size = convert( argv[1] ); if ( size < 0 ) throw ExceptionInst( cmd_error ); // invalid ? } // if fallthrough; case 1: ; // defaults default: // too many arguments throw ExceptionInst( cmd_error ); } // choose } catch( exception_t * ) { // catch any exit | "Usage: " | argv[0] | " [ size (>= 0) | 'd' (default " | DefaultSize | ") [ code (>= 0) | 'd' (default " | DefaultCode | ") [ input-file [ output-file ] ] ] ]"; } // try //sout | "size " | size | " code " | code; infile | nlOn; // read newline outfile | nlOff; // no implicit newline char ch; for () { // copy input file to output file infile | ch; // read a character if ( eof( infile ) ) break; // failed/eof ? outfile | ch; // write a character } // for } // main