×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to demonstrate the getopt() function

Here, we are going to demonstrate the getopt() function in C programming language? By Nidhi Last updated : March 10, 2024

C - getopt() function

The getopt() function is used to extract command line arguments. Here, we are writing a C program to demonstrators the getopt() function.

C program for getopt() function

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.

C Command Line Arguments Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.