Command-Line Arguments in C Programming Language

Many times, a program is developed that requires the user to enter a small amount of information at the terminal. This information might consist of a number indicating the triangular number that you want to have calculated or a word that you want to have looked up in a dictionary.

Rather than having the program request this type of information from the user, you can supply the information to the program at the time the program is executed. This capability is provided by what is known as command-line arguments.

As pointed out previously, the only distinguishing quality of the function main is that its name is special; it specifies where program execution is to begin. In fact, the function main is actually called upon at the start of program execution by the C system (known more formally  as the runtime system), just as you call a function from within your own C program. When main completes execution, control is returned to the runtime system, which then knows that your program has completed execution.

When main is called by the runtime system, two arguments are actually passed to the function. The first argument, which is called argc by convention (for argument count), is an integer value that specifies the number of arguments typed on the command line. The second argument to main is an array of character pointers, which is called argv by con- vention (for argument vector). There are argc + 1 character pointers contained in this array, where argc always has a minimum value of 0. The first entry in this array is a pointer to the name of the program that is executing or is a pointer to a null string if the program name is not available on your system. Subsequent entries in the array point to the values that were specified in the same line as the command that initiated execu- tion of the program. The last pointer in the argv array, argv[argc], is defined to be null.

To access the command-line arguments, the main function must be appropriately declared as taking two arguments. The conventional declaration that is used appears as follows:

int main (int argc, char *argv[])

{

}

Remember, the declaration of argv defines an array that contains elements of type “pointer to char.” As a practical use of command-line arguments, recall Program 10.10, which looked up a word inside a dictionary and printed its meaning.You can make use of command-line arguments so that the word whose meaning you want to find can be specified at the same time that the program is executed, as in the following command:

lookup aerie

This eliminates the need for the program to prompt the user to enter a word because it is entered on the command line.

If the previous command is executed, the system automatically  passes to main a point- er to the character string “aerie” in argv[1]. Recall that argv[0] contains a pointer to the name of the program, which in this case is “lookup”.

The main routine might appear as follows:

#include <stdlib.h>

#include <stdio.h>

int main (int argc, char *argv[])

{

const struct entry dictionary[100] =

   { { “aardvark”, “a burrowing African mammal”    },

{ “abyss”,  “a bottomless pit”             },

{ “acumen”, “mentally sharp; keen”          },

{ “addle”,  “to become confused”           },

{ “aerie”,  “a high nest”                  },

{ “affix”,  “to append; attach”            },

{ “agar”,   “a jelly made from seaweed”     },

{ “ahoy”,   “a nautical call of greeting”   },

{ “aigrette”, “an ornamental cluster of feathers” },

{ “ajar”,   “partially opened”             } };

int  entries = 10;

int  entryNumber;

int  lookup (const struct entry dictionary [], const char search[],

const int entries);

if ( argc != 2 )

{

fprintf (stderr, “No word typed on the command line.\n”);

return EXIT_FAILURE;

}

entryNumber = lookup (dictionary, argv[1], entries);

if ( entryNumber != -1 )

printf (“%s\n”, dictionary[entryNumber].definition);

else

printf (“Sorry, %s is not in my dictionary.\n”, argv[1]);

return EXIT_SUCCESS;

}

The main routine tests to make certain that a word was typed after the program name when the program was executed. If it wasn’t, or if more than one word was typed, the value of argc is not equal to 2. In this case, the program writes an error message to stan- dard error and terminates, returning an exit status of EXIT_FAILURE.

If argc is equal to 2, the lookup function is called to find the word pointed to by argv[1] in the dictionary. If the word is found, its definition is displayed.

As another example of command-line arguments, Program 16.3 was a file-copy pro- gram. Program 17.1, which follows, takes the two filenames from the command line, rather than prompting the user to type them in.

Program 17.1   File Copy Program Using Command-Line Arguments

// Program to copy one file to another — version 2

#include <stdio.h>

int main (int argc, char *argv[])

{

FILE *in, *out;

int  c;

if ( argc != 3 ) {

fprintf (stderr, “Need two files names\n”);

return 1;

}

if ( (in = fopen (argv[1], “r”)) == NULL ) {

fprintf (stderr, “Can’t read %s.\n”, argv[1]);

return 2;

}

if ( (out = fopen (argv[2], “w”)) == NULL ) {

fprintf (stderr, “Can’t write %s.\n”, argv[2]);

return 3;

}

while ( (c = getc (in)) != EOF )

putc (c, out);

printf (“File has been copied.\n”);

fclose (in);

fclose (out);

return 0;

}

The program first checks to make certain that two arguments were typed after the pro- gram name. If so, the name of the input file is pointed to by argv[1], and the name of the output file by argv[2]. After opening the first file for reading and the second file for writing, and after checking both opens to make certain they succeeded, the program copies the file character by character as before.

Note that there are four different ways for the program to terminate: incorrect num- ber of command-line arguments, can’t open the file to be copied for reading, can’t open the output file for writing, and successful termination. Remember, if you’re going to use the exit status, you should always terminate the program with one. If your program ter- minates by falling through the bottom of main, it returns an undefined exit status.

If Program 17.1 were called copyf and the program was executed with the following command line:

copyf foo foo1

then the argv array would look like Figure 17.1 when main is entered.

Remember that command-line arguments are always stored as character strings. Execution of the program power with the command-line arguments 2 and 16, as in

power 2 16

stores a pointer to the character string “2” inside argv[1], and a pointer to the string “16” inside argv[2]. If the arguments are to be interpreted as numbers by the program (as you might suspect is the case in the power program), they must be converted by the program itself. Several routines are available in the program library for doing such con- versions, such as sscanf, atof, atoi, strtod, and strtol. These are described in Appendix B, “The Standard C Library.”

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *