c++ 讓你的應用支援相對路徑

std::string GetCurrentExeDir()
{
  char szPath[1024] = { 0 };
#ifdef WIN32
  GetModuleFileName(NULL, szPath, 1024);
  char* p = strrchr(szPath, ‘\\’);
#else
  readlink(“/proc/self/exe”, szPath, sizeof(szPath));
  char* p = strrchr(szPath, ‘/’);
#endif
  *p = 0;
  return std::string(szPath);
}

BOOL SetCurrentWorkDir(std::string strPath)
{
  if (strPath.empty())
  {
    strPath = GetCurrentExeDir();
  }

#ifdef WIN32
  SetCurrentDirectory(strPath.c_str());
#else
  chdir(strPath.c_str());
#endif
  return TRUE;
}

先調用GetCurrentExeDir函數獲取exe路徑,然後使用結果設置SetCurrentWorkDir該函數參數即可,後續在應用程式裡面即可使用相對路徑

string strDir = GetCurrentExeDir();
SetCurrentWorkDir(strDir);