w3resource

Command-Line Arguments in C: Handling argc and argv

Understanding argc and argv in C

Overview:

In C programming, command-line arguments allow the user to pass information into the program when it starts executing. These arguments are passed via the ‘argc’ and ‘argv’ parameters of the main() function.

  • argc: Argument count, the number of command-line arguments passed.
  • argv: Argument vector, an array of strings (character pointers) representing the arguments.

Key Topics:

Let's explore this with practical examples.

Understanding argc and argv

int main(int argc, char *argv[]) {
. . . . . . 
. . . . . .
. . . . . .
}

argc (Argument Count):

  • argc stands for argument count and refers to the number of command-line arguments passed to the program.
  • This count includes the name of the program itself, so argc is always at least 1.

argv (Argument Vector):

  • argv is an array of character pointers (char*), where each element points to a string representing a command-line argument.
  • argv[0] always holds the name of the program (or the program's path if invoked with a path).
  • argv[1] to argv[argc-1] hold the additional arguments passed to the program.

Example: If a program is invoked as:

$ ./test arg1 arg2
  • argc = 3
  • argv[0] = "./test"
  • argv[1] = "arg1"
  • argv[2] = "arg2"

Example: Simple Command-Line Argument Program

This program prints out the number of command-line arguments passed and displays each argument, including the program's name.

Code:

#include <stdio.h>
// main function with argc (argument count) and argv (argument vector)
int main(int argc, char *argv[]) {
    // Check the number of arguments passed
    printf("Number of arguments: %d\n", argc);

    // Loop through and print each argument
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }
    return 0;
}

Output:

H:\Dev-Cpp\MinGW64\bin>test 4
Number of arguments: 2
Argument 0: test
Argument 1: 4

Explanation:

  • argc: It holds the number of command-line arguments. The first argument (argv[0]) is always the name of the program.
  • argv: It's an array of strings. Each string is a command-line argument, with argv[0] being the program name.
  • The program prints the total number of arguments and lists them.

Accessing command-line arguments

Command-line arguments can be accessed directly via the argv array. They are stored as strings (character arrays), so if numerical values are passed, they need to be converted using functions like atoi() or strtol().

Common ways to handle command-line arguments include:

  • Checking the number of arguments (argc): This ensures that the user has provided the required number of arguments.
  • Processing each argument (argv[]): Iterate through the argv[] array to access and process each argument.

Example: Accessing and Processing Command-Line arguments

Code:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    // Check if at least one argument (besides the program name) is passed
    if (argc < 2) {
        printf("Usage: %s <arg1> <arg2> ... <argN>\n", argv[0]);
        return 1;
    }

    // Print the total number of arguments
    printf("Total number of arguments (including program name): %d\n", argc);

    // Loop through and process each argument
    for (int i = 1; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);

        // Convert the argument to an integer and print it (if it is a valid number)
        int num = atoi(argv[i]);
        if (num != 0 || argv[i][0] == '0') {  // Checking if argument can be converted to an integer
            printf("Converted to integer: %d\n", num);
        } else {
            printf("'%s' is not a valid integer.\n", argv[i]);
        }
    }

    return 0;
}

Output:

H:\Dev-Cpp\MinGW64\bin>test 10 20 30 Hello
Total number of arguments (including program name): 5
Argument 1: 10
Converted to integer: 10
Argument 2: 20
Converted to integer: 20
Argument 3: 30
Converted to integer: 30
Argument 4: Hello
'Hello' is not a valid integer.

Explanation:

  • The program checks if at least one argument is passed (other than the program's name).
  • It prints the total number of arguments, including the program name (argv[0]).
  • Each argument is accessed from argv[] and printed.
  • If the argument is a valid integer, it's converted using atoi() and printed.
  • If the argument cannot be converted into an integer (e.g., it's a string like "Hello"), a message is printed indicating it's not a valid integer.

Handling Multiple Arguments

Often, programs need to accept multiple arguments, such as a file name, a number, or an option. To handle multiple command-line arguments:

  • Ensure that the number of arguments (argc) matches the expected count.
  • Access individual arguments via the argv array.
  • Validate and process the arguments as needed.

For example, if a program expects two arguments, you should check that argc == 3 (because argv[0] is the program name, and argv[1] and argv[2] are the two expected arguments).

Example: Handling Multiple Command-Line arguments

The program checks for two command-line arguments. If they are provided, it prints them; otherwise, it displays the correct usage of the program.

Code:

#include <stdio.h>

int main(int argc, char *argv[]) {
    // Check if the right number of arguments are provided
    if (argc < 3) {
        printf("Usage: %s <arg1> <arg2>\n", argv[0]);
        return 1;
    }
    // Print the first and second argument
    printf("Argument 1: %s\n", argv[1]);
    printf("Argument 2: %s\n", argv[2]);
    return 0;
}

Output:

H:\Dev-Cpp\MinGW64\bin>test 2 3
Argument 1: 2
Argument 2: 3
H:\Dev-Cpp\MinGW64\bin>test
Usage: test <arg1> <arg2>

Explanation:

  • This program expects two additional command-line arguments.
  • It checks whether enough arguments are provided (at least 3, including the program's name).
  • If not enough arguments are passed, it prints the usage message and exits with a return value of 1.
  • If arguments are passed, it prints the values of argv[1] and argv[2].

Example: Summing Command-Line Arguments (Integers)

This program takes numeric command-line arguments, converts them to integers, and prints their sum.

Code:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
    int sum = 0;
    // Start from index 1 as argv[0] is the program name
    for (int i = 1; i < argc; i++) {
        sum += atoi(argv[i]);  // Convert argument to integer and add to sum
    }
    printf("Sum of arguments: %d\n", sum);
    return 0;
}

Output:

H:\Dev-Cpp\MinGW64\bin>test 20 30
Sum of arguments: 50

Explanation:

  • The program accepts multiple command-line arguments, treats them as integers, and sums them.
  • It uses the atoi() function (from <stdlib.h>) to convert the string arguments to integers.
  • It skips argv[0], which is the program name, and starts summing from argv[1].


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/c-command-line-arguments.php