UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | 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 useage instructions in your file header comment to explain how to run the program.

#include <stdlib.h> #include <stdio.h> main(int argc, char** argv) { FILE *ifp, *ofp; 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); } ifp = fopen (argv[1], "r"); if (ifp == NULL) { printf("Sorry, couldn't open input file:\n"); printf("%s\n", argv[1]); exit (-2); } ofp = fopen (argv[2], "w"); if (ofp == NULL) { printf("Sorry, couldn't open output file:\n"); printf("%s\n", argv[2]); exit (-3); } . . . }


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