Search code examples
cinputgetopt

C getopt multiple value


My argument is like this

./a.out -i file1 file2 file3

How can I utilize getopt() to get 3 (or more) input files? I'm doing something like this:

while ((opt = getopt(argc, argv, "i:xyz.."))!= -1){
  case 'i':
     input = optarg; 
     break;
  ...
}

I get just the file1; how to get file2, file3?


Solution

  • If you must, you could start at argv[optind] and increment optind yourself. However, I would recommend against this since I consider that syntax to be poor form. (How would you know when you've reached the end of the list? What if someone has a file named with a - as the first character?)

    I think that it would be better yet to change your syntax to either:

    /a.out -i file1 -i file2 -i file3
    

    Or to treat the list of files as positional parameters:

    /a.out file1 file2 file3