获取和设置应用程序的工作目录

1.获取本exe的所在目录,在debug模式下,也可以获取到

std::string GetProcFolder(const char* module_name/* = NULL*/)
{
    std::string ret_str = "";
    char tempbuf[MAX_PATH];
    GetModuleFileNameA(GetModuleHandleA(module_name),tempbuf,MAX_PATH);
    int len = strlen(tempbuf);
    for(int i=len-1; i>0; i--)
    {
        if(tempbuf[i] == '\\')
        {
            tempbuf[i] = 0;
            ret_str = tempbuf;
            break;   
        }
    }
    return ret_str;
}

//调用实例
void main()
{
   string szPath = GetProcFolder("");
}

GetModuleFileNameA  获取当前进程已加载模块的文件的完整路径

GetModuleHandleA 获取一个应用程序或动态链接库的模块句柄



2.获取程序的工作目录

#include <direct.h>
main()
{
    char buf[80];
    getcwd(buf, sizeof(buf));
    printf("current working directory : %s\n", buf);
}

3.设置工作目录

安装程序从开始-》程序。。。启动时,工作目录很有可能是c:\windows\system32

为此,专门做了一个测试程序:

#include <Windows.h>
#include <direct.h>
#include <iostream>
using namespace std;

std::string GetProcFolder(const char* module_name)
{
	std::string ret_str = "";
	char tempbuf[MAX_PATH]={0};
	GetModuleFileNameA(GetModuleHandleA(module_name),tempbuf,MAX_PATH);
	int len = strlen(tempbuf);

	for (int i=len-1; i>0; i--)
	{
		if (tempbuf[i] == '\\')
		{
			tempbuf[i] = 0;
			ret_str = tempbuf;
			break;
		}
	}
	return ret_str;
}

int _tmain(int argc, _TCHAR* argv[])
{
	//getcwd
	string szGetCWD = getcwd(NULL,0);
	cout<<"getcwd=			"<<szGetCWD.c_str()<<endl;

	//GetCurrentDirectoryA
	char szCurDir[MAX_PATH]={0};
	GetCurrentDirectoryA(MAX_PATH,szCurDir);
	cout<<"GetCurrentDirectoryA=	"<<szCurDir<<endl;

	//GetProcFolder
	string strProcFolder = GetProcFolder("");
	cout<<"GetProcFolder=		"<<strProcFolder.c_str()<<endl;


	//GetModuleFileNameA
	char szModuleFile[MAX_PATH]={0};
	GetModuleFileNameA(NULL,szModuleFile,MAX_PATH);
	cout<<"GetModuleFileNameA=	"<<szModuleFile<<endl;

	//SetCurrentDirectoryA
	SetCurrentDirectoryA(strProcFolder.c_str());

	//getcwd
	string szGetCWD2 = getcwd(NULL,0);
	cout<<"getcwd=			"<<szGetCWD2.c_str()<<endl;

	getchar();
	return 0;
}


当程序直接运行,结果如下图所示:



当程序安装以后,从“开始”--》“程序” 里面运行,工作目录却变成了C:\windows\System32;

为了验证方便,可以找一个安装好的程序,替换成对应的exe名称;例如将测试程序,放到winrar的安装路径,并且修改成winrar.exe;

此时分别从程序启动,和从安装目录下直接启动,两者的运行目录是不一样的:


从“程序”菜单启动的工作目录变成了C:\windows\System32,而文件夹下直接双击的工作目录确实C:\Program Files\WinRAR;

所以,为了保证程序的可靠性,尽量先用

SetCurrentDirectoryA
设置工作目录。这样就可以高枕无忧了,比如一些相对路径也可以尽情使用。



posted on 2017-10-12 21:27  zhuxian2009  阅读(535)  评论(0编辑  收藏  举报

导航