我需要fstream
在Windows上使用我的C++应用程序访问某些文件.这些文件都位于我的exe文件所在文件夹的子文件夹中.
sea*_*n e 47
使用GetModuleHandle和GetModuleFileName来查找运行exe的位置.
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
GetModuleFileNameW(hModule, path, MAX_PATH);
Run Code Online (Sandbox Code Playgroud)
然后从路径中删除exe名称.
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)
归档时间: |
|
查看次数: |
48928 次 |
最近记录: |