如何解决尝试拆分 wchar 或其他函数以获取正在运行的应用程序的文件名
我在这里搜索了很多并尝试了几个示例,但仍然无法解决我的小问题。 我需要从路径中提取文件名“test.exe”。有人有一个可能有用的想法吗?另一种选择是通过另一个函数获取文件名?
提前致谢!
WCHAR fileName[255];
GetModuleFileName(NULL,fileName,255); // fileName = \TestFolder\test.exe
解决方法
#include <windows.h>
#include <shlwapi.h>
#pragma comment(lib,"Shlwapi.lib")
WCHAR fullPath[MAX_PATH];
GetModuleFileName(NULL,fullPath,MAX_PATH);
LPWSTR fileName = PathFindFileName(fullPath);
,
使用 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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。