Show List

Command-Line Arguments

In C, you can pass arguments to a program when you run it from the command line. These arguments are known as command-line arguments. Command-line arguments allow you to pass information to your program when you run it, such as the name of a file to process or the number of iterations to perform.

In C, the main function has a special signature that allows you to access the command-line arguments. The main function takes two arguments: argc and argv. argc is an integer that gives the number of arguments passed to the program, including the name of the program itself. argv is an array of character pointers, where each pointer points to a null-terminated string that gives an argument.

Here's an example of a simple program that prints out the command-line arguments:

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

If you compile this program and run it with the command ./a.out arg1 arg2 arg3, it will produce the following output:

less
Copy code
Number of arguments: 4 argv[0]: ./a.out argv[1]: arg1 argv[2]: arg2 argv[3]: arg3

As you can see, argc is 4, which includes the name of the program (./a.out) and the three arguments passed on the command line (arg1, arg2, and arg3). The argv array contains pointers to the strings of each argument, and argv[0] is always the name of the program itself.


    Leave a Comment


  • captcha text