Accessing Command-Line Arguments in C
In the C programming language, you can access command-line arguments passed to your program when it is executed. These arguments are typically used to provide input data or configuration options to the program.
Understanding Command-Line Arguments
When you run a C program from the command line, the operating system passes two pieces of information to the program:
-
argc
(argument count): This is an integer value that represents the number of command-line arguments, including the program name itself. -
argv
(argument vector): This is an array of strings, where each string represents a command-line argument. The first element,argv[0]
, is typically the name of the program being executed.
Here's an example of how the command-line arguments are structured:
In this example, the program is executed with three command-line arguments, so argc
is 4 (including the program name).
Accessing Command-Line Arguments
To access the command-line arguments in your C program, you need to declare the main()
function with the appropriate parameters:
int main(int argc, char *argv[]) {
// Your code here
return 0;
}
Here's an example of how you can use the argc
and argv
parameters to access the command-line arguments:
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of command-line arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
If you save this code in a file named command_line_args.c
and compile it with a C compiler (e.g., gcc command_line_args.c -o command_line_args
), you can run the program with command-line arguments like this:
./command_line_args arg1 arg2 arg3
The output will be:
Number of command-line arguments: 4
Argument 0: ./command_line_args
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
As you can see, the program can access the command-line arguments and print them out.
Real-World Example
Imagine you have a program that calculates the area of a rectangle. You can use command-line arguments to pass the length and width of the rectangle to the program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <length> <width>\n", argv[0]);
return 1;
}
int length = atoi(argv[1]);
int width = atoi(argv[2]);
int area = length * width;
printf("The area of the rectangle is: %d\n", area);
return 0;
}
In this example, the program expects two command-line arguments: the length and width of the rectangle. If the correct number of arguments is not provided, the program prints a usage message and returns an error code. Otherwise, it calculates the area and prints the result.
By using command-line arguments, you can make your C programs more flexible and reusable, as users can provide input data or configuration options without modifying the source code.