Qt设置生成exe为当前输出目录的工具类(原理win API调用)卲发所写

本文介绍了一个实用的C++类AfCd,该类提供了一系列功能,包括获取exe文件所在目录及切换当前工作目录的方法。这对于需要调整应用程序工作目录的开发者来说非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当前执行目录:程序调试输出的目录和exe文件执行的目录不一样

程序调试输出的目录:是代码执行的文件所在目录

exe文件执行目录:与exe同级。


#ifndef _AF_CD_H
#define _AF_CD_H

/* AfCd
   用于设置进程的"当前目录"

   作者:邵发
   版本:2016-01-05
   最新版本请在官网 http://afanihao.cn 上获取
*/

#include <string>
using std::string;

class AfCd
{
public:
	// 得到exe文件所在的目录 
	static string exeLocation(char seperator='\\');

	// 切换到目标位置 
	static void cd(const string& targetDir);

	// 切换到exe所有的位置 
	static void cd();
};

#endif




#ifdef _WIN32


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#include <windows.h>
#include "AfCd.h"


string AfCd::exeLocation(char seperator)
{
	// 得到exe文件的全路径
	char buf[512]={0};
	GetModuleFileNameA(NULL, buf, 512);


	// 替换分隔符
	string filePath = buf;
	if(seperator != '\\') //windows下默认是反斜线
	{
		for(int i=0; i<filePath.length(); i++)
		{
			if(filePath[i] == '\\') 
				filePath[i] = seperator;
		}
	}


	// 去除文件名,得到纯目录 
	int pos = filePath.rfind(seperator);
	string cd = filePath.substr(0, pos + 1);	
	return cd;
}


void AfCd::cd(const string& dir)
{
	SetCurrentDirectoryA(dir.c_str());
}


void AfCd::cd()
{
	string where = exeLocation('\\');
	cd(where);
}




#endif





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值