我试图将带有空格的参数传递给我通过CreateProcess()运行的批处理文件。如何指定整个对象是参数?
std::wstring args = TEXT("/C \"C:\\setup.bat\" C:\\TEST TEST");
在上面的示例中,我的批处理文件将第一个参数读为C:\ TEST。
并且,这不起作用(批处理文件立即退出并且不运行):
std::wstring args = TEXT("/C \"C:\\setup.bat\" \"C:\\TEST TEST\"");
以下是整个代码:
#include <iostream>
#define WINDOWS_LEAN_AND_MEAN
#include <Windows.h>
#include <strsafe.h>
#include <string>
#include <UserEnv.h>
#include <vector>
#define BUFSIZE 4096
#pragma comment(lib, "userenv.lib")
std::wstring GetEnvString()
{
wchar_t* env = GetEnvironmentStrings();
if (!env)
{
abort();
}
const wchar_t* var = env;
size_t total_len = 0;
size_t len;
while ((len = wcslen(var)) > 0)
{
total_len += len + 1;
var += len + 1;
}
std::wstring result(env, total_len);
FreeEnvironmentStrings(env);
return result;
}
int main()
{
LPVOID env;
if (!CreateEnvironmentBlock(&env, NULL, FALSE))
{
std::cout << "FAILURE" << std::endl;
system("PAUSE");
abort();
}
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(pi));
STARTUPINFO si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
std::wstring program = TEXT("C:\\Windows\\System32\\cmd.exe");
std::wstring args = TEXT("/C");
args.append(TEXT(" \"C:\\setup.bat\""));
args.append(TEXT(" C:\TEST TEST"));
std::vector<wchar_t> buf(args.begin(), args.end());
buf.push_back(0);
if (!CreateProcess(program.c_str(), buf.data(), NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi))
{
std::cout << "FAILURE" << std::endl;
system("pause");
abort();
}
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
DestroyEnvironmentBlock(env);
if (!CreateEnvironmentBlock(&env, NULL, FALSE))
{
std::cout << "FAILURE" << std::endl;
abort();
}
return 0;
}
答案 0 :(得分:1)
问题是/ C参数需要用引号括起的整个参数(如果它包含空格)。
所以,而不是cmd /c "c:\setup.bat" "c:\test test"
,您需要cmd /c ""c:\setup.bat" "c:\test test""
(或至少cmd /c "c:\setup.bat "c:\test test""
)
答案 1 :(得分:0)
想出来:
std::wstring args = TEXT("/C");
args.append(TEXT(" \"\"C:\\setup.bat\""));
args.append(TEXT(" \"C:\\TEST TEST\""));
我认为这最终会做类似的事情:cmd.exe&#34; C:\ setup.bat&#34; C:\ Test Test&#34;&#34;
答案 2 :(得分:-1)
这个怎么样:
std::wstring args = TEXT("/C \"C:\\setup.bat\" \"C:\\TEST\ TEST\"");