【问题标题】:Using wide strings with ifstream::open or multibyte strings with CreateProcess使用带有 ifstream::open 的宽字符串或带有 CreateProcess 的多字节字符串
【发布时间】:2012-04-19 11:53:55
【问题描述】:

我有一段代码,我需要在其中使用带有 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 与多字节字符串的问题。

有什么想法吗? 谢谢。

【问题讨论】:

  • 您可以使用例如mbstowcschar * 转换为wchar_t *

标签: c++ string


【解决方案1】:

我假设您定义了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()

【讨论】:

  • 是的 unicode 已定义,好的,现在我得到错误: CreateProcessA' : cannot convert parameter 2 from 'const char ' to 'LPSTR' 编辑 - 我不知道如何编辑这个正确,但斜体字是我写星号的地方,它们应该是指针,但 LPSTR 只是 char 对吗? =S
  • const char * 是 LPCSTR,这是 c_str() 返回的内容。然后你可能不得不将它复制到一个新的缓冲区中,但令人惊讶的是它当时没有给我警告或任何东西。编辑:没关系,它确实给了我一个警告>.
  • 这是因为 constness 的不同,它需要一个 LPSTR 而不是 LPCSTR,我可以在没有 const_cast 的情况下解决这个问题吗?
  • 我已经更新了我的答案。它现在可以毫无警告地编译(是的,这次我确定!)
猜你喜欢
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多