Command Line Arguments in C
In C, command-line arguments are a way to pass parameters to a C program when it is executed from the command line. These arguments are provided by the user when running the program and are used to customize the behavior of the program. Command-line arguments are typically provided after the program name in the command line.
Main Function Signature
In C, the main function is the entry point of the program. It can take two arguments: argc and argv.
- argc: The number of command line arguments, including the program name.
- argv: An array of pointers to strings, where each string is a command line argument.
Accessing Command-Line Arguments
You can access command-line arguments through the argv array. The first element (argv[0]) is the program's name, and the subsequent elements contain the user-provided arguments.
When you run the program with ./myprogram arg1 arg2, the output will be:
Multiple command line arguments
You can also pass multiple command line arguments to a program. For example, the following program takes two command line arguments and prints the sum of the two numbers to the console:
To compile and run this program, you would use the following commands:
gcc -o sum_test sum_test.c
./sum_test 10 20
Converting Command-Line Arguments
The arguments in argv are stored as strings, so if you need to use them as other data types, you'll need to convert them. For example, converting a string to an integer:
When you run the program with ./myprogram 42, the output will be:
Error Handling
It's essential to validate and handle command-line arguments correctly. Check argc to ensure the correct number of arguments are provided, and check the content of argv to ensure they meet your program's requirements. If they don't, provide appropriate error messages.
When you run the program with ./myprogram, it will display a usage message. When you run it as ./myprogram file.txt, it will process the file.
Conclusion
Command-line arguments are provided by users when running a program and are accessible through the argc and argv parameters in the main function. argc represents the number of arguments, while argv is an array of strings containing those arguments, allowing programs to be customized and configured with user input from the command line.