[英]Using wide strings with ifstream::open or multibyte strings with CreateProcess
我有一段代碼需要在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
,它應該工作正常(它確實對我來說)。
我不認為它會喜歡+操作。 將一個char數組顯式轉換為字符串。
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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.