I have a piece of code in which I need to use a string with both ifstream::open and CreateProcess, something like
//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. I always seem to run into problems with unicode vs multibyte strings.
Any ideas?
Thanks.
I’m assuming you defined
UNICODE. You can changeSTARTUPINFOtoSTARTUPINFOAandCreateProcesstoCreateProcessAand it should work fine (it did for me).I don’t think it’ll like the + operation though. Explicitly convert one char array to a string.
Finally, you’re going to need quotes around the beginning and end of
FILENAMEif it has a space.Edit:
Try putting this below your string declaration:
Then, use
charCmdLineinCreateProcessinstead ofcmdLine.c_str().