What is Command Line Argument in C language - Command Line Argument - What is Command Line Argument

What is Command Line Argument in C language? 



Command line arguments in C provide a way for a C program to receive input parameters directly from the command line when the program is executed. These arguments allow users to pass information to a C program when it starts running. Command line arguments are specified after the program name in the command line.

Here is a simple example to illustrate command line arguments in C:

#include <stdio.h>  

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

    // argc: Number of command line arguments (including the program name)

    // argv: Array of strings containing the command line arguments

    // Check if there are at least two arguments (including the program name)

    if (argc < 2) {

        printf("Usage: %s <argument1> [argument2 ...]\n", argv[0]);

        return 1;  // Exit the program with an error code

    }

    // Display the program name

    printf("Program Name: %s\n", argv[0]);

    // Display each command line argument

    printf("Command Line Arguments:\n");

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

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

    }

    return 0;  // Exit the program successfully

}

In this example: 

  • The main function has two parameters: argc (argument count) and argv (argument vector).
  • argc represents the total number of command line arguments, and argv is an array of strings where each element is a command line argument.
  • The program name is stored in argv[0], and user-specified arguments start from argv[1].

To compile and run this program, you could use commands like:

gcc program.c -o program

./program arg1 arg2 arg3

In the example above, ./program is the program name, and arg1, arg2, and arg3 are the command line arguments.

Keep in mind that all command line arguments are passed to the program as strings. If you need to process them as numbers, you may need to convert the strings to numeric values using functions like atoi() or atof() for integers and floating-point numbers, respectively. 

Comments