vs c++ 调试时的相对路径和exe双击运行时的相对路径不一样

vs c++在调试的时候,当前路径是cpp所在的文件夹,编译好之后,双击exe运行,当前路径又变成exe所在的路径,导致exe不能正常运行。
请问一下这个应该怎么处理

感谢邀请
你可以用下边函数,获取当前目录,用当前目录进行各种处理

inline void GetCurrentWorkDir(std::string &dir)
{
    char buf[256]; 
    memset(buf, 0, sizeof(buf));
    GetCurrentDirectoryA(sizeof(buf), buf);
    dir.append(buf);
}

正常,调试软件会更改exe的当前目录。你想要两种情况都能正常运行的话,应该加上代码获取exe所在目录路径,以这个路径为当前路径。

  • #include
    #include <Windows.h>

int main()
{
char szFilePath[MAX_PATH + 1] = { 0 };
GetModuleFileNameA(NULL, szFilePath, MAX_PATH);
(strrchr(szFilePath, '\'))[0] = 0; // 删除文件名,只获得路径字串
std::string path = szFilePath;
std::cout << path << std::endl;
std::cout << szFilePath << std::endl;
std::cout << "aaaaaa" << std::endl;
}