【问题标题】:GetModuleFileName fill an adress and not the executable name [duplicate]GetModuleFileName 填写地址而不是可执行文件名称 [重复]
【发布时间】:2020-07-28 03:48:44
【问题描述】:

我想获取我的 Windows 控制台应用程序的当前可执行应用程序名称。 根据this answer,解决方法应该是使用GetModuleFileNameA函数。

问题是函数没有填写可执行文件的名称而是填写地址:

#include <iostream>
#include <tchar.h>
#include <windows.h>

int main()
{
    TCHAR szFileName[MAX_PATH];
    GetModuleFileName(NULL, szFileName, MAX_PATH);
    std::cout << "My executable name is : " << szFileName << std::endl;
    system("pause");
}

输出:My executable name is : 0077F9DC

有人可以修复我的代码吗?

【问题讨论】:

  • 什么是TCHAR?是wchar_t 还是char?换句话说,您是否为 Unicode 编译?您还需要在调用 winapi 函数时包含错误检查。你忽略了GetModuleFileName 的返回值。不要那样做。
  • 您在std::cout &lt;&lt; szFileName 中遇到的问题。 GetModuleFileName 工作正确。但你的显示不正确。而是显示szFileName的内容你显示szFileName的地址
  • 将TCHAR 更改为char 和GetModuleFileName 更改为GetModuleFileNameA。该代码在输出行中混合了 Unicode 和非 Unicode,因此只输出缓冲区的地址。
  • 当 TCHAR 定义为 WCHAR 时,您应该使用 std::wcout(而不是 std::cout)进行输出。
  • @RichardCritten No. 将TCHAR 更改为wchar_t 并使用std::wcout。

标签: c++ winapi


【解决方案1】:

这是提取当前可执行文件名的完整代码:

#include <iostream>
#include <string>
#include <windows.h>

int main()
{
    wchar_t szFileName[MAX_PATH];
    // don't forget to check return values when calling winapi functions
    GetModuleFileNameW(NULL, szFileName, MAX_PATH); 
    std::wstring filePath(szFileName);
    std::size_t indexLastCharSlash = filePath.find_last_of(L"/\\");
    std::wstring fileName = filePath.substr(indexLastCharSlash + 1);
    std::wcout << fileName << std::endl;
    system("pause");
}

【讨论】:

  • 请不要鼓励使用 ANSI 文本。请不要鼓励忽视对 winapi 调用的错误检查。
  • 我不太明白问题出在哪里。如果您认为有必要,请编辑我的答案,但它会回答问题。我的代码与 UTF-8 不兼容吗?我想我们要记住它会打印文件名,所以字符是有限的。
  • 问题是您的代码无法处理流行的 ANSI 代码页之外的字符。您应该使用 Unicode,它在 winapi 中表示 wchar_t,然后使用 std::wcout 输出值。
  • 好的我明白了,谢谢你的反馈,但是像find_last_of和substr这样的功能与wstring不兼容所以我不知道如何适应它。
  • 它们与wstring兼容
猜你喜欢
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 2014-02-24
  • 2016-03-18
  • 2013-11-11
  • 2015-11-07
相关资源
最近更新 更多