/* This program tries to demonstrate the use of the command line arguments and file I/O. * Command line syntax is: * * ./a.out N [input-file [output-file]] * * where N is the number of strings to read, input-file is the optional name of the input file (defaults to stdin). If * output-file is specified, the input file must also be specified. The output file defaults to stdout if not specified. * * For example: * * ./a.out 3 * ./a.out 3 inputfile1 * ./a.out 3 inputfile1 outputfile1 */ #include int main( int argc, char *argv[] ) { char buffer[20]; FILE * in = stdin; /* in is initially set to standard input */ FILE * out= stdout; /* out is initially set to standard output */ int number = 0; int i; if ( argc > 4 ) { fprintf(stderr,"Specified too many arguments\n"); exit(-2); } else if ( argc < 2 ) { fprintf(stderr,"Did not specify required argument\n"); exit(-2); } /* if */ /* Note how the "break" statement only occurs in the lowest switch statement. * This means that if argc = 4, the statements for case 4, 3, and 2 will be executed. * If argc = 3, the statements for case 3 and 2 will be executed, etc. */ switch (argc) { case 4: out = fopen( argv[3], "w" ); if ( out == NULL ) { fprintf(stderr,"Error! Could not open the output file %s\n", argv[3]); exit(-3); } /* if */ case 3: in = fopen( argv[2], "r" ); if ( in == NULL ) { fprintf(stderr,"Error! Could not open the input file %s\n", argv[2]); exit(-3); } /* if */ case 2: number = atoi( argv[1] ); break; } /* switch */ if ( in == stdin ) { printf("Enter a list of words, each under 20 characters in length.\n"); printf("Press -d to signal EOF\n"); } /* if */ for ( i = 0; i < number; i += 1 ) { if ( fscanf(in, "%s", buffer) == EOF ) break; fprintf(out, "%s\n", buffer); } /* for */ }