如何将argv转换为CreateProcess的lpCommandLine参数?

我想编写一个启动另一个应用程序的应用程序。 像这样:

# This will launch another_app.exe my_app.exe another_app.exe # This will launch another_app.exe with arg1, arg and arg3 arguments my_app.exe another_app.exe arg1 arg2 arg3 

这里的问题是我在我的main函数中得到char* argv[] ,但是我需要将它合并到LPTSTR以便将它传递给CreateProcess

有一个GetCommandLine函数,但我无法使用它,因为我从Linux移植代码并绑定到argc/argv (否则,对我来说这是一个非常难看的黑客)。

我无法轻易地手动合并参数,因为argv[i]可能包含空格。

基本上,我想要CommandLineToArgvW的反向。 有没有标准的方法来做到这一点?

关于如何引用争论的最终答案在Daniel Colascione的博客上:

https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/

我不愿在这里引用代码,因为我不知道许可证。 基本思路是:

 for each single argument: if it does not contain \t\n\v\", just use as is else output " for each character backslashes = 0 if character is backslash count how many successive backslashes there are fi if eow output the backslashs doubled break else if char is " output the backslashs doubled output \" else output the backslashes (*not* doubled) output character fi rof output " fi // needs quoting rof // each argument 

如果需要将命令行传递给cmd.exe,请参阅文章(不同)。

我认为Microsoft C运行时库没有执行此操作的function是很疯狂的。

没有与CommandLineToArgvW()相反的Win32 API。 您必须自己格式化命令行字符串。 这只不过是基本的字符串连接。

Microsoft记录了命令行参数的格式(或者至少是VC ++所期望的格式 – 编写的应用程序,无论如何):

解析C ++命令行参数

解释操作系统命令行上给出的参数时,Microsoft C / C ++启动代码使用以下规则:

  • 参数由空格分隔,空格可以是空格或制表符。

  • 插入符(^)不被识别为转义字符或分隔符。 在传递给程序中的argv数组之前,该字符由操作系统中的命令行解析器完全处理。

  • 由双引号(“string”)包围的字符串被解释为单个参数,而不管其中包含的空格。 带引号的字符串可以嵌入参数中。

  • 以反斜杠(\“)开头的双引号被解释为文字双引号字符(”)。

  • 反斜杠按字面解释,除非它们紧跟在双引号之前。

  • 如果偶数个反斜杠后跟一个双引号,则每个反斜杠的argv数组中都会放置一个反斜杠,双引号将被解释为字符串分隔符。

  • 如果奇数个反斜杠后跟一个双引号,则每个反斜杠对argv数组放置一个反斜杠,双引号由剩余的反斜杠“转义”,从而产生文字双引号(“ )放入argv。

编写一个带有字符串数组并将它们连接在一起的函数应该不难,将上述规则的反向应用于数组中的每个字符串。

您需要重新创建命令行,负责将所有程序名称和参数括在" 。这是通过将\"连接到这些字符串来完成的,一个在开头,一个在最后。

假设要创建的程序名是argv[1] ,第一个参数是argv[2]等……

 char command[1024]; // size to be adjusted int i; for (*command=0, i=1 ; i 1) strcat(command, " "); strcat(command, "\""); strcat(command, argv[i]); strcat(command, "\""); } 

使用CreateProcess的第二个参数

 CreateProcess(NULL, command, ...); 

如果符合您的需要,您可以查看下面的代码,txt数组sz可以用作字符串指针。 我已经为Unicode和MBCS添加了代码支持,

  #include  #include  #ifdef _UNICODE #define String std::wstring #else #define String std::string #endif int _tmain(int argc, _TCHAR* argv[]) { TCHAR sz[1024] = {0}; std::vector allArgs(argv, argv + argc); for(unsigned i=1; i < allArgs.size(); i++) { TCHAR* ptr = (TCHAR*)allArgs[i].c_str(); _stprintf_s(sz, sizeof(sz), _T("%s %s"), sz, ptr); } return 0; }