C Programs Tutorials | IT Developer
IT Developer

C Programming - C Command Line Arguments



Share with a Friend

C Programming - C Command Line Arguments

Command Line Arguments in C

Command line arguments in C allow you to pass data to your program at the time of execution through the command line. This enables your program to take input directly from the command line, without the need for user interaction during the program's execution.

How Command Line Arguments Work

In C, command line arguments are passed to the main() function through its parameters, which are:

  • argc (Argument Count): An integer that represents the number of arguments passed to the program.
  • argv (Argument Vector): An array of character pointers (strings) representing the arguments.

The syntax of the main() function when using command line arguments is as follows:

C

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

Where:

  • argc: Number of command line arguments, including the name of the program itself.
  • argv[]: An array of strings where each string is one of the command line arguments.

How the Arguments Work:

  • argv[0] contains the name of the program itself.
  • argv[1] to argv[argc-1] contain the actual command line arguments provided by the user.

Example of Using Command Line Arguments:

Here is a simple C program that demonstrates the use of command line arguments:

C

#include <stdio.h>

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

    printf("Number of arguments: %d\n", argc);

    for (int i = 0; i < argc; i++) {

        printf("Argument %d: %s\n", i, argv[i]);

    }

    return 0;

}

Explanation:

  • argc gives the number of arguments (including the program name).
  • argv[i] is used to access each command line argument.
  • The program prints the number of arguments and then prints each argument.

Example Usage:

If you run the program from the command line like this:

./myprogram arg1 arg2 arg3

The output will be:

Number of arguments: 4

Argument 0: ./myprogram

Argument 1: arg1

Argument 2: arg2

Argument 3: arg3

Command Line Arguments for Practical Usage:

Command line arguments are often used for:

  • Passing file names to programs.
  • Setting configuration options or flags (e.g., -v for verbose).
  • Specifying input data or parameters for computations.

Example: Adding Two Numbers from Command Line:

This example demonstrates how to add two numbers passed as command line arguments:

C

#include <stdio.h>

#include <stdlib.h> // for atoi()

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

    if (argc != 3) {

        printf("Usage: %s <num1> <num2>\n", argv[0]);

        return 1;

    }

    int num1 = atoi(argv[1]);  // Convert the first argument to integer

    int num2 = atoi(argv[2]);  // Convert the second argument to integer

    int sum = num1 + num2;

    printf("Sum: %d\n", sum);

    return 0;

}

Explanation:

  • atoi() (ASCII to Integer) is used to convert the string arguments into integers.
  • The program expects two arguments representing numbers and calculates their sum.

Usage Example:

./add_numbers 12 30

Output:

makefile

Copy code

Sum: 42

Handling Non-integer Arguments:

If the arguments cannot be converted into integers (e.g., the user enters a non-numeric value), atoi() returns 0, which could lead to incorrect results. To handle such cases, you could use strtol() or manually validate input.

Using strtol() for Better Validation:

C

#include <stdio.h>

#include <stdlib.h>  // for strtol()

#include <errno.h>   // for errno

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

    if (argc != 3) {

        printf("Usage: %s <num1> <num2>\n", argv[0]);

        return 1;

    }

    char *endptr;

    int num1 = strtol(argv[1], &endptr, 10);

    if (*endptr != '\0') {

        printf("Error: '%s' is not a valid number.\n", argv[1]);

        return 1;

    }

    int num2 = strtol(argv[2], &endptr, 10);

    if (*endptr != '\0') {

        printf("Error: '%s' is not a valid number.\n", argv[2]);

        return 1;

    }

    int sum = num1 + num2;

    printf("Sum: %d\n", sum);

    return 0;

}

Explanation:

  • strtol() is used to convert the string to a long integer. It also allows error handling: if the input is not a valid number, the endptr will point to the invalid character, which can be checked.

Summary:

  • Command line arguments provide a way to pass input to programs at runtime.
  • Use argc for the number of arguments and argv[] to access the arguments.
  • Argument handling is important for ensuring proper program behavior when user inputs are passed.

Command line arguments make programs more flexible and interactive by allowing them to accept data when run, rather than requiring hard-coded values or manual input.