C++文件操作-获取当前工作路径的方法

1.采用GetCurrentDirectory,用于获取当前进程的当前目录

2.getcwd获取当前工作目录,类似上一方法

#include  <direct.h>  
#include  <stdio.h> 
 
char   buffer[MAX_PATH];   
getcwd(buffer, MAX_PATH); 
3.采用GetModuleFileName,用于获取所在exe/dll所在路径下的目录

TCHAR szPath[_MAX_PATH]={0};
TCHAR szDrive[_MAX_DRIVE]={0};
TCHAR szDir[_MAX_DIR]={0};
TCHAR szFname[_MAX_FNAME]={0}; 
TCHAR szExt[_MAX_EXT]={0};
 
GetModuleFileName(NULL,szPath,sizeof(szPath));  
 
ZeroMemory(g_wszProgramPath,sizeof(g_wszProgramPath));
 
_wsplitpath_s(szPath, szDrive, szDir, szFname, szExt);
wsprintf(g_wszProgramPath,_T("%s%s"), szDrive, szDir);
第二种获取写法

CString path;   
GetModuleFileName(NULL,path.GetBufferSetLength(MAX_PATH+1),MAX_PATH);   
path.ReleaseBuffer();   
int pos = path.ReverseFind('\\');   
path = path.Left(pos);
如果需要获取DLL所在路径,则在GetModuleFileName函数中第一个参数传入DLL对应的Module Handle,
这个Handle的获取:将DllMain中的hinstDLL保存(可以用全局变量保存),然后作为第一个参数传给GetModuleFileName

BOOL APIENTRY DllMain( HMODULE hModule,
     DWORD  ul_reason_for_call,
     LPVOID lpReserved
     )
其中,hModule可以通过如下方式获取

HMODULE h = GetModuleHandle("TestLibrary.dll");
--------------------- 

原文:https://blog.csdn.net/xuanyin235/article/details/77621615 

猜你喜欢

转载自blog.csdn.net/weixin_41265887/article/details/85227908