C Command Line Arguments

C Command Line Arguments


he full declaration of main looks like this:

1

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

The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.

The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. You can use each argv element just like a string, or use argv as a two dimensional array. argv[argc] is a null pointer.

How could this be used? Almost any program that wants its parameters to be set when it is executed would use this. One common use is to write a function that takes the name of a file and outputs the entire text of it onto the screen.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

#include <stdio.h>

 

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

{

    if ( argc != 2 ) /* argc should be 2 for correct execution */

    {

        /* We print argv[0] assuming it is the program name */

        printf( "usage: %s filename", argv[0] );

    }

    else

    {

        // We assume argv[1] is a filename to open

        FILE *file = fopen( argv[1], "r" );

 

        /* fopen returns 0, the NULL pointer, on failure */

        if ( file == 0 )

        {

            printf( "Could not open file\n" );

        }

        else

        {

            int x;

            /* read one character at a time from file, stopping at EOF, which

               indicates the end of the file.  Note that the idiom of "assign

               to a variable, check the value" used below works because

               the assignment statement evaluates to the value assigned. */

            while  ( ( x = fgetc( file ) ) != EOF )

            {

                printf( "%c", x );