如何获取原始命令行参数

mia*_*dao 11 c c++ windows

我需要将命令行参数从A.exe传递给B.exe.如果A.exe与多args一样

A.exe -a="a" -b="b"'

我可以使用

BeginProcess("B.exe", **args!**)

开始B.exe.我怎样才能获得原始命令行参数

'-a="a" -b="b"'

use*_*353 11

如果您使用的是Windows,则使用GetCommandLine获取原始命令行.

请注意,GetCommandLine还包含argv [0].因此,在将其传递给B之前,您必须从GetCommandLine的输出中超越argv [0].

这是一些非错误检查的代码

#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;

}
Run Code Online (Sandbox Code Playgroud)

当我运行上面的程序时A.exe -a="a" -b="b",我得到以下输出

A.exe -a="a" -b="b"
Command Line is : -a="a" -b="b"
Run Code Online (Sandbox Code Playgroud)

  • 不要使用此代码。如果可执行文件名称用引号括起来(即使其路径中没有空格也可能发生),它将失败。有关正确的实现,请查看 [Wine 对 CommandLineToArgvW 的实现](https://github.com/wine-mirror/wine/blob/master/dlls/shell32/shell32_main.c)。@harry-johnston:除非您生成自己的副本,否则您仍然需要删除可执行路径以将其替换为您要运行的程序。 (2认同)

ben*_*nrg 7

这是基于Wine 对 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++;
Run Code Online (Sandbox Code Playgroud)

注意!当前的 Wine 实现,截至 2 月 19 日 2'20 - git commit a10267172,现在从dlls/shell32/shell32_main.cdlls/shcore/main.c.