VS2010/MFC 获取当前程序路径的方法

第一种方法

DWORD GetCurrentDirectory(
  DWORD nBufferLength,  // size, in characters, of directory buffer
  LPTSTR lpBuffer       // pointer to buffer for current directory
);
BOOL SetCurrentDirectory( LPCTSTR lpPathName
// pointer to name of new current directory );

 第二种方法

用GetModuleFileName得到应用程序的文件名(第一个参数为NULL)
再用_splitpath分析文件名得到路径
例如:
复制代码
//得到当前路径
 /*char buf[100];
 GetCurrentDirectory(sizeof(buf),buf);
 MessageBox(buf);
 HINSTANCE hInst=NULL;
 hInst=AfxGetApp()->m_hInstance;
 char path_buffer[_MAX_PATH];
 GetModuleFileName(hInst,path_buffer,sizeof(path_buffer));//得到exe文件的全路径
 //分离路径和文件名。
    char drive[_MAX_DRIVE];
    char dir[_MAX_DIR];
    char fname[_MAX_FNAME];
    char ext[_MAX_EXT];
 _splitpath( path_buffer, drive, dir, fname, ext );
 CString Path;
 Path.Format("%s%s",drive,dir);
char path[300];
strcpy(path,drive);
strcat(path,dir);
复制代码

又或:

复制代码
TCHAR exeFullPath[MAX_PATH];
    CString strPath;
    GetModuleFileName(NULL,exeFullPath,MAX_PATH);
    strPath=(CString)exeFullPath;
    int position=strPath.ReverseFind('\\');
    strPath=strPath.Left(position+1); 
    TCHAR FilePath[MAX_PATH];
    GetModuleFileName(NULL,FilePath,MAX_PATH);
    (_tcsrchr(FilePath,'\\'))[1] = 0;//// 删除文件名,只获得路径字串   // C:\**\**\
    lstrcat(FilePath,_T("MY.ini")); 
复制代码

 第三种方法

VC中__argv[0]可以得到exe的程序名,然后用_splitpath可以分解得到程序路径。

 第四种方法

#include<direct.h>
char buf[_MAX_PATH];
_getcwd(buf,_MAX_PATH);

 第五种方法

是得到操作系统所在的目录
char buf[100];
 GetSystemDirectory(buf,100);
 MessageBox(buf);

 

posted @   rainbow70626  阅读(3832)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
历史上的今天:
2019-01-05 OpenGL ES SL 3.0规范中以前的attribute改成了in varying改成了out
2017-01-05 基于GPU的高分一号影像正射校正的设计与实现
点击右上角即可分享
微信分享提示