Hi, I need to use getopt for a program called like myprogram.c file1 file2 file3 -t. Now I've read some examples about how to use switch cases for options with hypens (-t). But I don't get how to write this for my file1, file2, and file3 (they are arguments that must be provided). It would help if someone could explain getopt in simple terms as well, I feel like my brain is fried at this point with all the variables I read about it having. Thank you kindly!

Show how you are using getopt() in your code. Just talking about it isn't helpful without something tangible to work from.

FWIW, the Linux getopt() man page has several pages of documentation and examples to help. Here is one of the examples:

       /* The following trivial example program uses getopt() to handle two  program  options:  -n,  with  no  associated
       value; and -t val, which expects an associated value. */

       #include <unistd.h>
       #include <stdlib.h>
       #include <stdio.h>

       main(int argc, char *argv[])
           int flags, opt;
           int nsecs, tfnd;

           nsecs = 0;
           tfnd = 0;
           flags = 0;
           while ((opt = getopt(argc, argv, "nt:")) != -1) {
               switch (opt) {
               case 'n':
                   flags = 1;
               case 't':
                   nsecs = atoi(optarg);
                   tfnd = 1;
               default: /* '?' */
                   fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",

           printf("flags=%d; tfnd=%d; optind=%d\n", flags, tfnd, optind);

           if (optind >= argc) {
               fprintf(stderr, "Expected argument after options\n");

           printf("name argument = %s\n", argv[optind]);

           /* Other code omitted */


Edited 1 Year Ago by rubberman

This question has already been answered. Start a new discussion instead.