0

I am not sure how to use the getopt command in my scenario. I want the following input command:

mydiff file1 file2

So there are no options just the two filenames. Any idea on how to do that?

alk
  • 69,737
  • 10
  • 105
  • 255
craaaft
  • 211
  • 1
  • 8
  • 1
    Is `getopt` required? You could just declare `int main(int argc, char * argv[])` and take the filenames from `argv[]`. – Arc676 Nov 04 '15 at 08:46
  • "*how to use the getopt command*" just don't. Use `main()`'s arguments directly. – alk Nov 04 '15 at 08:46
  • Related, if not a duplicate: http://stackoverflow.com/q/18079340/694576 – alk Nov 04 '15 at 08:48

1 Answers1

1

If your program does not accept POSIX-style options, then alk has the right of it - you don't need getopt() if you have no options to get.

Per the getopt(3) manpage, once getopt() has exhausted the provided options (which, being options, may be zero in number), it returns (int) -1 and sets optind to the index of the first non-opt argument in argv[] which, in your example, would be argv[1] -> file1.

Darwin von Corax
  • 5,201
  • 3
  • 17
  • 28
  • OK I got it. How could I check if there are any options and if there really are I want to give out an error. At the moment I get an inavlid option message. I guess I could do if(getopt(argc,argv,"")!=-1) then error. – craaaft Nov 04 '15 at 11:08
  • You could try that and see what happens, but I'm not aware of any stock Unix tools that explicitly check for unwanted _types_ of args. The most I've ever done in this sort of situation is something like `if (argc < MINARGS || argc > MAXARGS)` where `MAXARGS = 3` and `MINARGS = 3` (or `MINARGS = 1` if we can run as a filter.) – Darwin von Corax Nov 04 '15 at 17:10