Command-Line Arguments with getopt in C

 Command-Line Arguments with getopt in C


The getopt function allows you to handle command-line arguments and options in a more structured manner. It simplifies the parsing of command-line arguments and provides support for both short and long options.



#include <stdio.h>

#include <unistd.h>


int main(int argc, char* argv[]) {

    int opt;

    while ((opt = getopt(argc, argv, "af:")) != -1) {

        switch (opt) {

            case 'a':

                printf("Option -a is specified\n");

                break;

            case 'f':

                printf("Option -f is specified with value: %s\n", optarg);

                break;

            default:

                printf("Unknown option: %c\n", opt);

                break;

        }

    }


    for (int i = optind; i < argc; i++) {

        printf("Non-option argument: %s\n", argv[i]);

    }


    return 0;

}

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...