Upon completion of this short, you will be able to:
In a C program, the command line arguments are passed as parameters to the main()
function. The argc parameter represents the number of arguments passed, and the argv parameter is an array of strings that contains the arguments.
Here’s an example of how to print out the command line arguments passed to a C program:
#include <stdio.h>
int main(int argc, char *argv[]) {
int i;
("Number of arguments: %d\n", argc);
printf
for (i = 0; i < argc; i++) {
("Argument %d: %s\n", i, argv[i]);
printf}
return 0;
}
In this example, the argc parameter contains the number of arguments passed to the program, and argv is an array of strings that contains the arguments. The program uses a for loop to iterate over the elements of the argv array and prints out each argument.
You can compile and run this program with command-line arguments like this:
% gcc example.c -o example
% ./example arg1 arg2 arg3
In this example, the program is compiled with the gcc compiler and then run with the ./example command, followed by the arguments “arg1”, “arg2”, and “arg3.” The output of the program is:
Number of arguments: 4
Argument 0: ./example
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3
Here’s an example of how to modify the code to call different functions based on the command line argument:
#include <stdio.h>
#include <string.h>
void handle_get() {
("Handling GET request\n");
printf}
void handle_put() {
("Handling PUT request\n");
printf}
int main(int argc, char *argv[]) {
if (argc != 2) {
("Usage: %s [GET|PUT]\n", argv[0]);
printfreturn 1;
}
if (strcmp(argv[1], "GET") == 0) {
();
handle_get} else if (strcmp(argv[1], "PUT") == 0) {
();
handle_put} else {
("Invalid command: %s\n", argv[1]);
printfreturn 1;
}
return 0;
}
In this example, there added two new functions: handle_get()
and handle_put()
, which will be called depending on the command line argument that is passed in. The program also some error handling to ensure that the program is called with the correct number of arguments.
If the program is called with one argument, the program will check whether the argument is “GET” or “PUT” using the strcmp()
function. If the argument is “GET”, the program will call handle_get()
, and if the argument is “PUT”, the program will call handle_put()
. If the argument is anything else, the program will print an error message and exit.
You can compile and run this program with command-line arguments like this:
$ gcc example.c -o example
$ ./example GET
Command line arguments allow the user to pass input parameters to a C program when it is executed. This enables the program to be more flexible and customizable, as different inputs can be used to modify the program’s behavior without having to modify the source code.
None collected yet. Let us know.