Windows VC++ 调整进程当前目录为程序可执行文件所在目录

本文配套程序下载地址为:http://download.csdn.net/detail/morewindows/5165721

转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/8683519

欢迎关注微博:http://weibo.com/MoreWindows

 

    调整进程当前目录为程序可执行文件所在目录是个非常实用的方法。为了更加的让代码复用,本文将调整进程当前目录为程序可执行文件所在目录这一功能封装为三个实用函数——

1SplitPathFileName

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

2GetProcessPathNameAndFileName

得到当前进程可执行文件的路径名,文件名,后缀名。

3AdjustProcessCurrentDirectory

调整进程当前目录为程序可执行文件所在目录

 

各函数使用示范可以参见如下程序:

//调整进程当前目录为程序可执行文件所在目录
//http://blog.csdn.net/morewindows/article/details/8683519
//By MoreWindows( http://blog.csdn.net/MoreWindows )
#include <windows.h>
#include <stdio.h>
#include <conio.h>

//将文件全名(带路径)分解成路径名,文件名,后缀名
//C:\test\test.exe -> "C:\test\", "test", ".exe"
//By MoreWindows( http://blog.csdn.net/MoreWindows )
void SplitPathFileName(const char *pstrPathFileName, char *pstrPath, char *pstrFileName, char *pstrExtName)
{
	if (pstrPath != NULL)
	{
		char szTemp[MAX_PATH];
		_splitpath(pstrPathFileName, pstrPath, szTemp, pstrFileName, pstrExtName);
		strcat(pstrPath, szTemp);
	}
	else
	{
		_splitpath(pstrPathFileName, NULL, NULL, pstrFileName, pstrExtName);
	}
}

//得到当前进程可执行文件的路径名,文件名,后缀名
//如运行C:\test\test.exe 得到 "C:\test\", "test", ".exe"
//By MoreWindows( http://blog.csdn.net/MoreWindows )
BOOL GetProcessPathNameAndFileName(char *pstrPath, char *pstrFileName, char *pstrExtName)
{
	char szExeFilePathFileName[MAX_PATH];
	if (GetModuleFileName(NULL, szExeFilePathFileName, MAX_PATH) == 0)
		return FALSE;
	
	SplitPathFileName(szExeFilePathFileName, pstrPath, pstrFileName,pstrExtName);
	return TRUE;
}

//调整进程当前目录为程序可执行文件所在目录
//By MoreWindows( http://blog.csdn.net/MoreWindows )
BOOL AdjustProcessCurrentDirectory()
{
	char szPathName[MAX_PATH];
	GetProcessPathNameAndFileName(szPathName, NULL, NULL);
	return SetCurrentDirectory(szPathName);
}



int main()
{
	printf("    调整进程当前目录为程序可执行文件所在目录 \n");        
	printf(" - http://blog.csdn.net/morewindows/article/details/8683519 -\n");
	printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");  

	char szCurrentDirectory[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
	printf("进程当前目录为: \n%s\n", szCurrentDirectory);

	AdjustProcessCurrentDirectory();

	GetCurrentDirectory(MAX_PATH, szCurrentDirectory);
	printf("\n调整后,进程当前目录为: \n%s\n", szCurrentDirectory);
	getch();
	return 0;
}

通过CMD来调用这个程序看看。

 

由图可以看出,程序的当前目录已经被调整到程序可执行文件所在目录了。

 

附1:得到程序所在目录还可以使用PathRemoveFileSpec函数。20130507

 

本文配套程序下载地址为:http://download.csdn.net/detail/morewindows/5165721

转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/8683519

欢迎关注微博:http://weibo.com/MoreWindows


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值