c++ - 试图拆分 wchar 或其他函数以获取正在运行的应用程序的文件名
问题描述
我在这里搜索了很多并尝试了几个示例,但仍然无法解决我的小问题。我需要从路径中提取文件名“test.exe”。有人有一个可行的想法吗?其他选项是通过另一个函数获取文件名?
提前致谢!
WCHAR fileName[255];
GetModuleFileName(NULL, fileName, 255); // fileName = \TestFolder\test.exe
解决方案
使用 WinApi
#include <iostream>
#include <string>
#include <windows.h>
std::string GetExecutableName()
{
std::string path = std::string(MAX_PATH, 0);
if( !GetModuleFileNameA(nullptr, &path[0], MAX_PATH ) )
{
throw std::runtime_error(u8"Error at get executable name.");
}
size_t pos=path.find_last_of('/');
if(pos == std::string::npos)
{
pos = path.find_last_of('\\');
}
return path.substr(pos+1);
}
int main()
{
std::cout<< GetExecutableName() << std::endl;
return 0;
}
使用主要参数
首先 - arg[0] 包含可执行文件的完整文件名。
#include <iostream>
#include <string>
std::string GetExecutableName(const std::string& exe)
{
size_t pos=exe.find_last_of('/');
if(pos == std::string::npos)
{
pos =exe.find_last_of('\\');
}
return exe.substr(pos+1);
}
int main(int argc,char ** args) {
std::cout << GetExecutableName(args[0])<< std::endl;
}
推荐阅读
- apache - Apache 因自分配 SSL 和 MAMP Pro 5 而失败
- jsf - iCal4j 和使用 primefaces p.schedule
- linux - cd 到虚拟环境而不是采购它
- django - 将 json 作为 celery 任务的一部分插入 postgres
- laravel - Laravel - 使用相同的 v-model 选择表单
- reporting-services - 在 SSRS 中动态传递文本框值
- javascript - Javascript-锁定字符串以防止其他方法更改它
- javascript - 用于从 javascript 呈现 UI 元素的 Html 助手
- php - 带破折号的 imap_search
- apache - Apache 的模块文件夹中缺少 Mod_ssl