您的位置:首页 > 其它

C/MFC如何获得应用程序当前路径(整理)

2012-08-23 14:15 399 查看
第一种方法:
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;

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: