Command Line Arguments in C

  • What are Command Line Arguments?
  • Command-line arguments in C are parameters provided to a program when it is executed from a command line interface (CLI). They allow users to pass information to the program at runtime, making the program more flexible and dynamic. These arguments are passed to the main function, which can be defined to accept them.

  • Main Function with Command-Line Arguments :
  • In C, the main function can be defined to accept command-line arguments as follows :

    C Code
    #include <stdio.h> main(int argc, char *argv[]) { int i; printf("Number of arguments: %d\n", argc); for (i = 0; i < argc; i++) { printf("Argument %d: %s\n", i, argv[i]); } }

    Explanation :
    - argc (argument count) : This is an integer that indicates the number of command-line arguments passed to the program, including the program name.
    - argv (argument vector) : This is an array of strings (character pointers) representing the command-line arguments. argv[0] is the name of the program, and argv[1] to argv[argc-1] are the actual command-line arguments.

  • Example usage :
  • 1. Save the above program as example.c.
    2. Compile the program using a C compiler, e.g., gcc:
    gcc -o example example.c
    3. Run the program with command-line arguments :
    ./example arg1 arg2 arg3
    4. Output :
    Number of arguments: 4
    Argument 0: ./example
    Argument 1: arg1
    Argument 2: arg2
    Argument 3: arg3

  • Example program :
  • C Code
    #include <stdio.h> #include <stdlib.h> main(int argc, char *argv[]) { if (argc != 3) { printf("Usage: %s <num1> <num2>\n", argv[0]); return 1; } int num1 = atoi(argv[1]); int num2 = atoi(argv[2]); int sum = num1 + num2; printf("Sum: %d\n", sum); }

    Sum : 15

    C Code
    #include <stdio.h> #include <stdlib.h> main(int argc, char *argv[]) { if (argc < 2) { printf("Usage: %s <number1> <number2> ... <numberN>\n", argv[0]); return 1; } int i; double sum = 0.0; for (i = 1; i < argc; i++) { sum += atof(argv[i]); } double average = sum / (argc - 1); printf("Average: %.2f\n", average); }

    Average: 30.00

  • Conclusion :
  • Command-line arguments significantly enhance the usability, flexibility, and functionality of C programs by allowing dynamic input, enabling automation, simplifying testing, promoting standardization, and improving resource management. They make programs more adaptable to different use cases and environments, which is essential for developing robust and efficient software.