How to get the raw command line arguments

If you are on Windows, you use GetCommandLine to get the raw command line.

Note that GetCommandLine also includes argv[0]. So you will have to go beyond argv[0] from the output of GetCommandLine before passing it to B.

This is some non-error checked code to do that

#include <string.h>
#include <windows.h>
#include <iostream>
#include <ctype.h>

int main(int argc, char **argv)
{
    LPTSTR cmd  = GetCommandLine();

    int l = strlen(argv[0]);

    if(cmd == strstr(cmd, argv[0]))
    {
        cmd = cmd + l;
        while(*cmd && isspace(*cmd))
            ++cmd;
    }

    std::cout<<"Command Line is : "<<cmd;

}

When I run the above program as A.exe -a="a" -b="b", I get the following output

A.exe -a="a" -b="b"
Command Line is : -a="a" -b="b"

Here is the one and only correct way to skip the executable name, based on Wine's implementation of CommandLineToArgvW:

char *s = lpCmdline;
if (*s == '"') {
    ++s;
    while (*s)
        if (*s++ == '"')
            break;
} else {
    while (*s && *s != ' ' && *s != '\t')
        ++s;
}
/* (optionally) skip spaces preceding the first argument */
while (*s == ' ' || *s == '\t')
    s++;

Note! Current Wine implementation, as of Feb 19 2'20 - git commit a10267172, is now moved from dlls/shell32/shell32_main.c to dlls/shcore/main.c.

Tags:

Windows

C++

C