C++ [Windows]可执行文件所在文件夹的路径

asa*_*sas 32 c++ windows

我需要fstream在Windows上使用我的C++应用程序访问某些文件.这些文件都位于我的exe文件所在文件夹的子文件夹中.

  • 什么是最简单,最重要的:获取当前可执行文件夹路径的最安全方法?

sea*_*n e 47

使用GetModuleHandleGetModuleFileName来查找运行exe的位置.

HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
Run Code Online (Sandbox Code Playgroud)

然后从路径中删除exe名称.

  • 没有Win32 API,有没有办法做到这一点? (2认同)
  • @asas:不,不是一种简单而安全的方式. (2认同)
  • @asas:在不使用Win32 API的情况下编写C ++ Windows应用程序?喜欢使用Qt吗? (2认同)
  • 我知道这确实很旧,但是 `GetModuleFileNameW(NULL, path, MAX_PATH)` 还不够吗? (2认同)

Nat*_*ate 23

GetThisPath.h

/// dest is expected to be MAX_PATH in length.
/// returns dest
///     TCHAR dest[MAX_PATH];
///     GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
Run Code Online (Sandbox Code Playgroud)

GetThisPath.cpp

#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
    if (!dest) return NULL;
    if (MAX_PATH > destSize) return NULL;

    DWORD length = GetModuleFileName( NULL, dest, destSize );
    PathRemoveFileSpec(dest);
    return dest;
}
Run Code Online (Sandbox Code Playgroud)

mainProgram.cpp

TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
Run Code Online (Sandbox Code Playgroud)

更新:PathRemoveFileSpec在Windows 8中已弃用.但是替换,PathCchRemoveFileSpec仅在Windows 8+中可用.(感谢@askalee的评论)

我认为下面的代码可能会有效,但我将上面的代码留在那里,直到下面的代码被审查.我目前没有设置编译器来测试它.如果您有机会测试此代码,请发表评论,说明以下代码是否有效以及您测试的操作系统.谢谢!

GetThisPath.h

/// dest is expected to be MAX_PATH in length.
/// returns dest
///     TCHAR dest[MAX_PATH];
///     GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
Run Code Online (Sandbox Code Playgroud)

GetThisPath.cpp

#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
    if (!dest) return NULL;

    DWORD length = GetModuleFileName( NULL, dest, destSize );
#if (NTDDI_VERSION >= NTDDI_WIN8)
    PathCchRemoveFileSpec(dest, destSize);
#else
    if (MAX_PATH > destSize) return NULL;
    PathRemoveFileSpec(dest);
#endif
    return dest;
}
Run Code Online (Sandbox Code Playgroud)

mainProgram.cpp

TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
Run Code Online (Sandbox Code Playgroud)

  • `PathRemoveFileSpec`的+1,不知道. (7认同)
  • 似乎不推荐使用PathRemoveFileSpec:http://msdn.microsoft.com/en-us/library/windows/desktop/bb773748(v = vs.85).aspx,请改用PathCchRemoveFileSpec. (3认同)
  • @askalee似乎值得注意的是,它仅受Win8(及以上)桌面应用程序的支持 (2认同)