类名称:AfCd.h和AfCd_Win32.cpp
//AfCd.h
#include <string>
using std::string;
class AfCd
{
public:
//得到exe文件所在的目录
static string exeLocation(char seperator = '\\');
//切换到目标位置
static void cd(const string& targetDir);
//切换到exe所有的位置
static void cd();
};
//AfCd_Win32.cpp
#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 != '\\')
{
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);
}
//测试代码
AfCd::cd();//设置当前目录
FILE* fp = fopen("123.txt", "wb");
fwrite("hello", 1, 5, fp);
fclose(fp);