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!

I am not a Unix/Linux user so I am not 100% sure but after reading on GetOpt here and a GetOpt example here I would say the short answer is you must write myprogram.c -t file1 file2 file3 because it parses for options first.

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>

       int
       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;
                   break;
               case 't':
                   nsecs = atoi(optarg);
                   tfnd = 1;
                   break;
               default: /* '?' */
                   fprintf(stderr, "Usage: %s [-t nsecs] [-n] name\n",
                           argv[0]);
                   exit(EXIT_FAILURE);
               }
           }

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

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

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

           /* Other code omitted */

           exit(EXIT_SUCCESS);
       }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.