Win32 API command line arguments parsing

2019-01-26 05:03发布

I'm writing Win32 console application, which can be started with optional arguments like this:

app.exe /argName1:"argValue" /argName2:"argValue"

Do I have to parse it manually (to be able to determine, which arguments are present) from argc/argv variables, or does Win32 API contain some arguments parser?

9条回答
祖国的老花朵
2楼-- · 2019-01-26 05:40

The only support that Win32 provides for command line arguments are the functions GetCommandLine and CommandLineToArgvW. This is exactly the same as the argv parameter that you have for a console application.

You will have to do the parsing yourself. Regex would be a good option for this.

查看更多
在下西门庆
3楼-- · 2019-01-26 05:40

Not sure about existence of such a win32 api function(s), but Boost.Program_Options library could help you.

查看更多
对你真心纯属浪费
4楼-- · 2019-01-26 05:40

If your needs are simple, you might want to take a look at Argh!.
It is single header and super easy to use:

int main(int, char* argv[])
{
    argh::parser cmdl(argv);          // declare

    if (cmdl[{ "-v", "--verbose" }])  // use immediately
        std::cout << "Verbose, I am.\n";

    return EXIT_SUCCESS;
}

By being unintrusive, it doesn't take over you main() function.

From the Readme:

Philosophy

Contrary to many alternatives, argh takes a minimalist laissez-faire approach, very suitable for fuss-less prototyping with the following rules:

The API is:

  • Minimalistic but expressive:
    • No getters nor binders
    • Just the [] and () operators.
    • Easy iteration (range-for too).
  • You don't pay for what you don't use;
  • Conversion to typed variables happens (via std::istream >>) on the user side after the parsing phase;
  • No exceptions thrown for failures.
  • Liberal BSD license;
  • Single header file;
  • No non-std dependencies.

argh does not care about:

  • How many '-' preceded your option;
  • Which flags and options you support - that is your responsibility;
  • Syntax validation: any command line is a valid (not necessarily unique) combination of positional parameters, flags and options;
  • Automatically producing a usage message.
查看更多
登录 后发表回答