Command-Line Arguments in C
Introduction
Command-line arguments are a way to pass parameters to a C program when it's executed in a command-line environment. They allow users to customize the behavior of a program without modifying the source code. In this guide, we'll explore how to work with command-line arguments in C and provide sample code to illustrate their usage.
Command-Line Arguments
Command-line arguments are typically passed to a C program when it's run from the terminal. They are stored as strings and can be accessed from the program's main()
function. The common format for running a C program with command-line arguments is:
./program_name arg1 arg2 arg3 ...
Accessing Command-Line Arguments
In C, the command-line arguments are passed to the main()
function as parameters. The first parameter, argc
, represents the number of arguments, and the second parameter, argv
, is an array of strings containing the arguments. Here's how you can access them:
int main(int argc, char *argv[]) {
// argc is the argument count
// argv is the argument vector (array of strings)
// Access and process command-line arguments
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\\n", i, argv[i]);
}
return 0;
}
Sample Code
Let's explore some examples of working with command-line arguments in C:
Printing Command-Line Arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
// Print all command-line arguments
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\\n", i, argv[i]);
}
return 0;
}
Calculating the Sum of Numbers
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s num1 num2 ...\\n", argv[0]);
return 1;
}
int sum = 0;
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]);
}
printf("Sum of numbers: %d\\n", sum);
return 0;
}
Conclusion
Command-line arguments are a powerful feature in C programming, allowing users to customize program behavior without altering the source code. This guide has introduced you to the basics of working with command-line arguments in C, including accessing arguments and providing sample code for printing arguments and calculating the sum of numbers. As you continue your C programming journey, you'll find command-line arguments to be a valuable tool for creating versatile and user-friendly applications.