[英]Using wide strings with ifstream::open or multibyte strings with CreateProcess
I have a piece of code in which I need to use a string with both ifstream::open and CreateProcess, something like 我有一段代码需要在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 requires a LPCWSTR, so to use the string with CreateProcess I would need to declare the filename and 'cmdLine' as std::wstring, but ifstream::open doesn't take wide strings...I can't figure a way to get around this. CreateProcess需要一个LPCWSTR,因此要将字符串与CreateProcess一起使用,我需要将文件名和'cmdLine'声明为std :: wstring,但是ifstream :: open不会使用宽字符串...我无法找到方法解决这个问题。 I always seem to run into problems with unicode vs multibyte strings.
我似乎总是遇到Unicode和多字节字符串的问题。
Any ideas? 有任何想法吗? Thanks.
谢谢。
I'm assuming you defined UNICODE
. 我假设您定义了
UNICODE
。 You can change STARTUPINFO
to STARTUPINFOA
and CreateProcess
to CreateProcessA
and it should work fine (it did for me). 您可以更改
STARTUPINFO
到STARTUPINFOA
和CreateProcess
到CreateProcessA
,它应该工作正常(它确实对我来说)。
I don't think it'll like the + operation though. 我不认为它会喜欢+操作。 Explicitly convert one char array to a string.
将一个char数组显式转换为字符串。
std::string cmdLine = (std::string)"/c " + FILENAME;
Finally, you're going to need quotes around the beginning and end of FILENAME
if it has a space. 最后,如果
FILENAME
有空格,您将需要在引号的开头和结尾加上引号。
const char FILENAME = "\"C:\\Program Files\\Company\\Program\\program.exe\"";
^ ^ ^
Edit: Try putting this below your string declaration: 编辑:尝试将其放在您的字符串声明下面:
char charCmdLine [MAX_PATH + 3]; //"/c " is 3 extra chars
strncpy (charCmdLine, cmdLine.c_str(), MAX_PATH + 3);
Then, use charCmdLine
in CreateProcess
instead of cmdLine.c_str()
. 然后,在
CreateProcess
使用charCmdLine
而不是cmdLine.c_str()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.