The getopt() function is used to extract command line arguments. Here, we are writing a C program to demonstrators the getopt() function.
Program:
The source code to demonstrate the getopt() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to demonstrate the getopt() function
#include <stdio.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int option = 0;
while ((option = getopt(argc, argv, ":if:lrx")) != -1) {
switch (option) {
case 'i':
case 'l':
case 'r':
printf("option: %c\n", option);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case ':':
printf("Option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
while (optind < argc) {
printf("Extra arguments: %s\n", argv[optind]);
optind++;
}
return 0;
}
Output:
$ gcc main.c -o main
$ ./main -i myfile.txt -lr -x "includehelp"
option: i
option: l
option: r
extra arguments: myfile.txt
extra arguments: includehelp
Explanation:
In the main() function, we used the getopt() function to extract arguments from the command line based on given options and then printed the result on the console screen.
The getopt() function is used to extract command line arguments. Here, we are writing a C program to demonstrators the getopt() function.
Program:
The source code to demonstrate the getopt() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
Output:
Explanation:
In the main() function, we used the getopt() function to extract arguments from the command line based on given options and then printed the result on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer