Command Line Arguments in C

Command-line arguments are a common way to parameterize execution of programs. For example, gcc hello.c -o hello uses hello.c and -o hello as arguments to the gcc program.

#include <stdio.h>

int main(int argc, char *argv[]) {
    // argc provides the number of command-line arguments.
    // argv is an array of strings containing the program name
    // and all the arguments.

    // This is equivalent to argsWithProg in the original example
    char **argsWithProg = argv;

    // This is equivalent to argsWithoutProg in the original example
    char **argsWithoutProg = argv + 1;

    // You can get individual args with normal indexing.
    char *arg = argv[3];

    // Print all arguments including program name
    printf("Arguments with program name:\n");
    for (int i = 0; i < argc; i++) {
        printf("%s\n", argv[i]);
    }

    // Print arguments without program name
    printf("\nArguments without program name:\n");
    for (int i = 1; i < argc; i++) {
        printf("%s\n", argv[i]);
    }

    // Print the fourth argument (index 3)
    printf("\nFourth argument: %s\n", arg);

    return 0;
}

To experiment with command-line arguments, it’s best to compile the program first:

$ gcc command_line_arguments.c -o command_line_arguments
$ ./command_line_arguments a b c d
Arguments with program name:
./command_line_arguments
a
b
c
d

Arguments without program name:
a
b
c
d

Fourth argument: c

In C, command-line arguments are passed to the main function through the parameters int argc (argument count) and char *argv[] (argument vector). The argc parameter contains the number of arguments, and argv is an array of strings containing the arguments.

The first element of argv (index 0) is always the name of the program itself. The actual command-line arguments start from index 1.

Note that in C, we need to manually iterate through the argv array to print all arguments, unlike the automatic printing in the original example.

Next, we’ll look at more advanced command-line processing with option parsing libraries like getopt.