Search code examples
cgetopt

C forcing getopt to stop at first non argument


I am coding an programm proxy which redirects stdout and so on into files, with usage: proxy [-i infile] [-o outfile] [-e errfile] cmd [options].

So i want to force getopt to stop when it arrives at cmd because it should not parse the options for .

I read about the environment variable POSIXLY_CORRECT but I want so make it independent of that.

So my question is how to reach exactly that.

A part of my code so far

while ((opt = getopt (argc, argv, "i:o:e:")) != -1)
  switch (opt)
  {
    case 'i':
      i = 1;
      strcpy(input, optarg);
      break;
    case 'o':
      o = 1;
      strcpy(output, optarg);
      break;
    case 'e':
      e = 1;
      strcpy(error, optarg);
      break;
    default:
      fprintf(stderr, "usage: proxy [-i infile] [-o outfile] [-e errfile] <cmd> [options]\n");
      return -1;
  }

This will enter the default case all the time when an option for cmd is given :(


Solution

  • You are being bitten by GNU getopt's doubtful behaviour of reordering parameters before entry. As you found out, one solution is to set the environment variable POSIXLY_CORRECT before the first call to getopt. You can also disable this behaviour by passing + as the first character of the getopt string:

    opt = getopt(argc, argv, "+i:o:e:")