当前执行目录:程序调试输出的目录和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