将宽字符串与 ifstream::open 一起使用,或者将多字节字符串与 CreateProcess 一起使用
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
,它应该可以正常工作(它为我做到了)。
我不认为它会喜欢 + 操作。将一个字符数组显式转换为字符串。
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()
。
相关文章:
- 有没有办法在C++将字符串与开关语句一起使用?
- 我如何将 OR 与 if 语句一起使用字符串
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 将 NULL 与 C 的字符* 字符串一起使用
- C++程序在将 int 与 cin 一起使用时有效,但不能使用字符串
- 编译器如何将链表中的地址字符串在一起?
- 将find_last_of与字符串C++一起使用
- 在 c++ 中将 find_first_of 与字符串一起使用,而不是一组预定义字符
- 如何将adjacent_find与字符串C++一起使用
- 可以将std::getline()与从std::string中移出的字符串一起使用吗
- 如何在不使用模板的情况下将variadic函数与字符串一起使用
- 将 dirent->d_name 与字符串一起使用失败
- 如何将开关与字符串一起使用
- 将两个字符串一起分配,获取访问读取冲突
- C++ - 将 sendto() 与基本字符串一起使用
- 如何在C++中将 atoi 函数与字符串一起使用
- 将 <null> printf 与字符串一起使用
- 除非我通过data()或C_str()运行cout,否则无法将它与C++字符串一起使用
- C++-将.at()方法与字符串一起使用时出现问题
- 如何将replace_if与字符串一起使用