您的位置:首页 > 其它

设置当前exe执行文件为进程工作目录

2015-07-13 16:58 302 查看
设置当前exe执行文件为进程工作目录

两种办法:

1, API

void _splitpath(
   const char *path,
   char *drive,
   char *dir,
   char *fname,
   char *ext 
);


这个函数将文件全名(带路径)分解成路径名,文件名,后缀名。

2, API

BOOL PathRemoveFileSpec(      
    LPTSTR pszPath
);


使用例子:

#include <windows.h>
#include <iostream>
#include <Shlwapi.h>		//PathRemoveFileSpec函数头文件
#pragma comment(lib, "shlwapi.lib")			//VS2013下需加才可以使用PathRemoveFileSpec

using namespace std;

int main()
{
	char szCurrentDirectory[MAX_PATH], szExeFilePathFileName[MAX_PATH];

	//获取当前进程工作目录
	GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
	//szCurrentDirectory == 输出 E:\Projects\1
	cout << "进程当前工作目录为: " << szCurrentDirectory <<endl;
	//szExeFilePathFileName == exe的路径是 E:\Projects\1\Debug\11.exe
	GetModuleFileName(NULL, szExeFilePathFileName, MAX_PATH);
	char drive[MAX_PATH], dir[MAX_PATH], fname[MAX_PATH], ext[MAX_PATH];
	//szExeFilePathFileName == exe的路径 E:\Projects\1\Debug\11.exe
	//drive == E:   盘符
	//dir == \Projects\1\Debug\  文件中间的路径
	//fname == 11   不带拓展名的文件名
	//ext == .exe   文件拓展名
	//第一种办法获得exe文件目录
	_splitpath(szExeFilePathFileName, drive, dir, fname, ext);
	//把盘符和文件中间路径组合起来E:\Projects\1\Debug\  
	strcat(drive, dir);

	GetModuleFileName(NULL, szExeFilePathFileName, MAX_PATH);
	//第二种办法获得exe文件目录
	//szExeFilePathFileName == E:\Projects\1\Debug\11.exe 
	PathRemoveFileSpec(szExeFilePathFileName);

	//设置进程工作目录szExeFilePathFileName == E:\Projects\1\Debug
	SetCurrentDirectory(szExeFilePathFileName);
	//获得进程工作目录
	GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
	//szCurrentDirectory == E:\Projects\1\Debug
	cout << "调整后,  进程的工作目录为: " << szCurrentDirectory << endl;
	system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: