首页 > 解决方案 > 试图拆分 wchar 或其他函数以获取正在运行的应用程序的文件名

问题描述

我在这里搜索了很多并尝试了几个示例,但仍然无法解决我的小问题。我需要从路径中提取文件名“test.exe”。有人有一个可行的想法吗?其他选项是通过另一个函数获取文件名?

提前致谢!

WCHAR fileName[255];

GetModuleFileName(NULL, fileName, 255);   // fileName = \TestFolder\test.exe

标签: c++arraysstringsplitchar

解决方案


使用 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;
}

推荐阅读