c++系列文章目录
文章目录
前言
在编程中经常会用到文件路径,如果写绝对路径,把工程复制到另一台机器上,在别人机器上路径就错误了,所以最好用相对路径,这样工程拷贝到其他机器上也不用修改文件路径了。
一、获取工程路径
得到xxxxx.vcxproj 目录
string getFilePath()
{
char* path = nullptr;
path = _getcwd(nullptr, 1);
puts(path);
string filePath(path);
return filePath;
delete path;
path = nullptr;
}
二、获取可执行文件路径
得到xxx.exe路径,注意GetModuleFileName会得到路径+“xxxx.exe”
string TCHAT_to_string(TCHAR* STR)
{
int iLen = WideCharToMultiByte(CP_ACP, 0, STR, -1, nullptr, 0, nullptr, nullptr);
char* chRtn = new char[iLen * sizeof(char)];
WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen, nullptr, nullptr);
string str(chRtn);
int pos = str.find_last_of("\\", str.length());
string exePath = str.substr(0, pos);
return exePath;
}
string getExePath()
{
TCHAR szExePath[MAX_PATH];
GetModuleFileName(nullptr, szExePath, sizeof(szExePath));
string exePath = TCHAT_to_string(szExePath);
}