What is the alternative to getopt function on Wind

2019-06-25 08:50发布

问题:

This question already has an answer here:

  • getopt.h: Compiling Linux C-Code in Windows 8 answers

The code below I'm using Posix C:

while ((opt = getopt(argc, argv, "a:p:h")) != -1)

How can I port this code to Windows C++ using an alternative function?

Thanks

回答1:

If you had searched you would have found another thread that goes over some compatibility libraries for getopt, among other implementations, for Windows based systems.

getopt.h: Compiling Linux C-Code in Windows

On another note, you could always use the va_arg, va_list, va_start, and va_end functions to process arguments as well.

/* va_arg example */
#include <stdio.h>      /* printf */
#include <stdarg.h>     /* va_list, va_start, va_arg, va_end */

int FindMax (int n, ...)
{
  int i,val,largest;
  va_list vl;
  va_start(vl,n);
  largest=va_arg(vl,int);
  for (i=1;i<n;i++)
  {
    val=va_arg(vl,int);
    largest=(largest>val)?largest:val;
  }
  va_end(vl);
  return largest;
}

int main ()
{
  int m;
  m= FindMax (7,702,422,631,834,892,104,772);
  printf ("The largest value is: %d\n",m);
  return 0;
}

Reference: http://www.cplusplus.com/reference/cstdarg/va_list/



回答2:

Microsoft has provided a nice implementation (as well as some other helpers) inside the open source IoTivity project here you could possibly re-use (pending any licensing requirements you may have):

Take a look at the "src" and "include" directories here for "getopt.h/.c".

https://github.com/iotivity/iotivity/tree/master/resource/c_common/windows