如果从文件中读取,则无法按文件名运行进程
Can't run process by Filename if read from file
LPCSTR __FileName = "program.exe";
void ProcessRun(LPCSTR pszExeName)
{
PROCESS_INFORMATION piProcInfoGPS;
STARTUPINFO siStartupInfo;
SECURITY_ATTRIBUTES saProcess, saThread;
ZeroMemory(&siStartupInfo, sizeof(siStartupInfo));
siStartupInfo.cb = sizeof(siStartupInfo);
saProcess.nLength = sizeof(saProcess);
saProcess.lpSecurityDescriptor = NULL;
saProcess.bInheritHandle = true;
saThread.nLength = sizeof(saThread);
saThread.lpSecurityDescriptor = NULL;
saThread.bInheritHandle = true;
CreateProcess(NULL, (LPTSTR)pszExeName, &saProcess, &saThread, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcInfoGPS);
__hProcess = piProcInfoGPS.hProcess;
__ProcessID = piProcInfoGPS.dwProcessId;
}
如果我__FileName传递给函数,程序将运行。但是,当我从 ini 文件中读取文件名时
[Launcher]
FileName=program.exe
char INIValue[256];
GetPrivateProfileString("Launcher", "FileName", "nan.exe", INIValue, 256, ".\BackgroundConfig.ini");
string temp(INIValue);
__FileName = temp.c_str();
然后尝试将文件名传递给函数,它不会运行。到底是什么原因造成的?文件名完全相同。
您尚未显示足够的代码来确定这是问题所在,但请考虑以下事项:
char * someString;
void foo()
{
std::string str("whatever");
doSomethingWithCharStar(str.c_str()); // fine: str's data has not been destroyed yet
someString = str.c_str();
} // uh-oh, here the std::string's memory will be deleted
void bar()
{
foo(); // sets someString
doSomethingWithCharStar(someString); // by the time we get here, though, the memory pointed to by someString is freed
}
上面的代码调用未定义的行为(假设doSomethingWithCharStar
取消引用传入的指针)。不应将char*
存储为全局,而应存储std::string
。更好的是,根本不要使用全局:
std::string foo()
{
return std::string("whatever");
}
void bar()
{
std::string value(foo());
doSomethingWithCharStar(value.c_str());
}
请注意,在上面的第一个代码段中遇到的问题本质上与返回对局部变量的引用时的问题相同。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 从命令行c++发送文本文件名
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- GDB 在程序运行时打印文件名行号
- 运行正则表达式时未选中的异常 - 从文件路径获取不带扩展名的文件名
- 我可以在运行时更改 Log4Qt 配置的文件名吗?
- 如何在C++中获取当前运行的可执行文件的文件名
- 如果从文件中读取,则无法按文件名运行进程
- c++:如何运行以字符串和文件名作为参数的程序
- 打开文件名运行环境
- 获取运行文件名:argv[0] vs boost::filesystem::current_path()
- 打开并读取在运行时指定文件名的文件