Example using command line arguments

This example uses command line arguments to give the program the name of the input file to use and the name of the output file to write during processing. This is a very common use of command line arguments.

If your program needs command line arguments in order to run, then you should have a clearly marked usage instructions in your file header comment to explain how to run the program.

/********************************************** * File: exampleargs.c * Author: S. Bogar * Date: ?? * Modified: 9/26/05 * Section: 0101 * Email: bogar@cs.umbc.edu * * A program to demonstrate the use of command-line * arguments. It demonstrates how to open files and * do some error-checking ***********************************************/ #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { FILE *ifp, *ofp; /* check that the number of arguments on the command line * is correct */ if (argc != 3) { printf ("This program requires command line arguments\n"); printf ("that are the name of the input file to be\n"); printf ("used, and the name of the output file to\n"); printf ("be used\n"); exit (-1); } /* open the input file */ ifp = fopen (argv[1], "r"); if (ifp == NULL) { printf("Sorry, couldn't open input file:\n"); printf("%s\n", argv[1]); exit (-2); } /* open the output file */ ofp = fopen (argv[2], "w"); if (ofp == NULL) { printf("Sorry, couldn't open output file:\n"); printf("%s\n", argv[2]); exit (-3); } . . . }