gpt4 book ai didi

c++ - 将宽字符串与 ifstream::open 一起使用或将多字节字符串与 CreateProcess 一起使用

转载 作者:行者123 更新时间:2023-11-28 08:06:21 28 4
gpt4 key购买 nike

我有一段代码,我需要在其中使用带有 ifstream::open 和 CreateProcess 的字符串,例如

//in another file
const char* FILENAME = "C:\\...blah blah\\filename.bat";

// in main app
std::ifstream is;
is.open(FILENAME);
// ...do some writing
is.close();

STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );

std::string cmdLine = "/c " + FILENAME;

if( !CreateProcess( "c:\\Windows\\system32\\cmd.exe",
cmdLine.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) )
{
return GetLastError();
}

CreateProcess 需要一个 LPCWSTR,因此要将字符串与 CreateProcess 一起使用,我需要将文件名和“cmdLine”声明为 std::wstring,但 ifstream::open 不采用宽字符串...我不能想办法解决这个问题。我似乎总是遇到 unicode 与多字节字符串的问题。

有什么想法吗?谢谢。

最佳答案

我假设您定义了 UNICODE。您可以将 STARTUPINFO 更改为 STARTUPINFOA 并将 CreateProcess 更改为 CreateProcessA,它应该可以正常工作(它对我有用)。

不过我认为它不会喜欢 + 操作。将一个字符数组显式转换为字符串。

std::string cmdLine = (std::string)"/c " + FILENAME;

最后,如果 FILENAME 有空格,您需要在开头和结尾加上引号。

const char FILENAME = "\"C:\\Program Files\\Company\\Program\\program.exe\"";
^ ^ ^

编辑:试着把它放在你的字符串声明下面:

char charCmdLine [MAX_PATH + 3]; //"/c " is 3 extra chars
strncpy (charCmdLine, cmdLine.c_str(), MAX_PATH + 3);

然后,在 CreateProcess 中使用 charCmdLine 而不是 cmdLine.c_str()

关于c++ - 将宽字符串与 ifstream::open 一起使用或将多字节字符串与 CreateProcess 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10227470/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com