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

设置当前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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值