C Programming Tutorial

C Programming Tutorial

Command Line Arguments in C

Command line arguments in C Programming are a way for a user to pass input data to a program while executing it through the command prompt or terminal. These arguments are passed as an array of strings, where each string represents a single argument. The main function in a C program can accept these arguments, allowing the program to be more versatile and interactive.

How command line arguments work in C:

1. Modify the main function: To accept command line arguments, you need to modify the main function’s signature to include two parameters: int argc and char *argv[] (or char **argv). argc stands for “argument count” and represents the number of arguments passed, while argv stands for “argument vector” and is an array of character pointers containing the actual arguments.

    int main(int argc, char *argv[]) {
        // Your code here
    }
    

    2. Access the arguments: Inside the main function, you can access the command line arguments using the argv array. The first element argv[0] contains the name of the program itself, and the subsequent elements contain the arguments passed by the user. Note that the arguments are passed as strings, so you may need to convert them to the desired data type (e.g., using atoi() for integers).

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

      3. Compile and run the program: After writing the program, compile it using a C compiler (e.g., gcc), and then run the compiled executable, passing the command line arguments as needed. For example:

        $ gcc myprogram.c -o myprogram
        $ ./myprogram arg1 arg2 arg3
        

        When the program is executed, it will process the command line arguments and display the output accordingly.

        Remember that since command line arguments are passed as strings, you will need to convert them to the appropriate data types before using them in arithmetic operations or other tasks that require specific data types.

        Share This Article