获取Visual Studio项目名(或exe文件名)以在C++程序中使用它
Get Visual Studio project name (or exe file name ) to use it inside a C++ program
我需要在我的C++程序中执行这个命令:
WinExec("program_name.exe", SW_SHOW);
我正在使用Visual Studio 2010。有没有什么方法可以使用变量、常量或其他东西来避免字符串"program_name.exe"?现在它在我的计算机上运行,但我的程序将在另一台计算机上测试,我不知道项目.exe文件的名称。
可执行文件名称作为参数传递到主函数中:
int main(int argc, char **argv)
{
string exename = argv[0];
}
(详细说明abdul的答案:)
WinExec函数为您检查错误,您可以在下面的代码中看到。如果您感兴趣,可以在此处阅读有关WinExec功能的更多信息。
让我们来看看函数语法:
UINT WINAPI WinExec(
_In_ LPCSTR lpCmdLine,
_In_ UINT uCmdShow
);
由于LPCSTR
(指向Const字符串的长指针)实际上是const string
,因此可以将字符串类型作为其第一个参数进行传递,但需要将其转换为Const char*,这实际上是一个LPCSTR
(指向Const字符串的长指针)。在下面的代码中,它是通过使用c_str()
来完成的。
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main()
{
string appName="yourappname.exe";
int ExecOutput = WinExec(appName.c_str(), SW_SHOW);
/*
If the function succeeds, the return value is greater than 31.
If the function fails, the return value is one of the following error values.
0 The system is out of memory or resources.
ERROR_BAD_FORMAT The .exe file is invalid.
ERROR_FILE_NOT_FOUND The specified file was not found.
ERROR_PATH_NOT_FOUND The specified path was not found.
*/
if(ExecOutput > 31){
cout << appName << " executed successfully!" << endl;
}else {
switch(ExecOutput){
case 0:
cout << "Error: The system is out of memory or resources." << endl;
break;
case ERROR_BAD_FORMAT:
cout << "Error: The .exe file is invalid." << endl;
break;
case ERROR_FILE_NOT_FOUND:
cout << "Error: The specified file was not found." << endl;
break;
case ERROR_PATH_NOT_FOUND:
cout << "Error: The specified path was not found." << endl;
break;
}
}
return 0;
}
我特意排除了(abdul创建的)另一个函数,以避免被您的问题所迷惑,并让您更清楚地了解WinExec函数的实际用途。你可以很容易地添加他创建的应用程序检查功能,并在其中放入你需要的任何其他检查
您可以将要运行的.exe文件存储在与运行它的.exe文件相同的位置,这样您就可以保持硬编码的常量名称。
或者,一个很好的方法是通过命令行参数传入要运行的程序名称,下面是解析参数的教程:教程
这样,您就可以用变量替换该字符串,并在运行.exe.
打开conf文件读取应用程序名称,测试应用程序是否存在保存路径,然后传递到函数
这只是一个例子,相同的想法
int main()
{
string appName;
if (getAppName(appName))
{
WinExec(appName.c_str(), SW_SHOW);
/// WinExec(appName, SW_SHOW);
/// ^^^ one of these
}
return 0;
}
函数看起来像这个
bool getAppName(string& appName)
{
string str;
///file open, and read;
///read(str)
if(fileExist(str))
{
appName = str;
return true;
}
return false;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址