UMBC CMSC 201
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

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)
   {
      fprintf (stderr, "This program requires command line arguments\n");
      fprintf (stderr, "that are the name of the input file to be\n");
      fprintf (stderr, "used, and the name of the output file to\n");
      fprintf (stderr, "be used\n");
      exit (-1);
   }

   /* open the input file */
   ifp = fopen (argv[1], "r");
   if (ifp == NULL)
   {
      fprintf(stderr, "Sorry, couldn't open input file:\n");
      fprintf(stderr, "%s\n", argv[1]);
      exit (-2);
   }

   /* open the output file */
   ofp = fopen (argv[2], "w");
   if (ofp == NULL)
   {
      fprintf(stderr, "Sorry, couldn't open output file:\n");
      fprintf(stderr, "%s\n", argv[2]);
      exit (-3);
   }

    .
    .
    .

}


CSEE | 201 | 201 F'06 | lectures | news | help