将宽字符串与 ifstream::open 一起使用,或者将多字节字符串与 CreateProcess 一起使用

Using wide strings with ifstream::open or multibyte strings with CreateProcess

本文关键字:字符串 一起 多字节 CreateProcess 或者 open ifstream      更新时间:2023-10-16

我有一段代码,其中我需要使用一个同时包含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更改为STARTUPINFOACreateProcess更改为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()