是否有一种平台不可知和文件系统不可知的方法来获取程序运行的目录的完整路径?不要与当前工作目录混淆。(请不要推荐库,除非它们是像clib或STL这样的标准库。)

(如果没有平台/文件系统不可知的方法,也欢迎在Windows和Linux中针对特定文件系统工作的建议。)


当前回答

这是来自cplusplus论坛

在windows上:

#include <string>
#include <windows.h>

std::string getexepath()
{
  char result[ MAX_PATH ];
  return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );
}

在Linux上:

#include <string>
#include <limits.h>
#include <unistd.h>

std::string getexepath()
{
  char result[ PATH_MAX ];
  ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX );
  return std::string( result, (count > 0) ? count : 0 );
}

在hp - ux上:

#include <string>
#include <limits.h>
#define _PSTAT64
#include <sys/pstat.h>
#include <sys/types.h>
#include <unistd.h>

std::string getexepath()
{
  char result[ PATH_MAX ];
  struct pst_status ps;

  if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)
    return std::string();

  if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)
    return std::string();

  return std::string( result );
}

其他回答

对于Win32, GetCurrentDirectory应该做到这一点。

对于控制台的Windows系统,可以使用system(dir)命令。控制台提供目录等信息。在cmd下阅读有关dir命令的信息。但是对于类unix系统,我不知道…如果执行了该命令,请读取bash命令。Ls不显示目录…

例子:

int main()
{
    system("dir");
    system("pause"); //this wait for Enter-key-press;
    return 0;
}

这个问题是15年前问的,所以现在现有的答案是不正确的。如果你使用的是c++ 17或更高版本,现在的解决方案非常简单:

#include <filesystem>

std::cout << std::filesystem::current_path();

更多信息请参见cppreference.com。

在POSIX平台上,可以使用getcwd()。

在Windows上,您可以使用_getcwd(),因为使用getcwd()已被弃用。

对于标准库,如果Boost对您来说足够标准,那么我会建议Boost::filesystem,但是他们似乎已经从建议中删除了路径规范化。您可能必须等到TR2可以随时获得完全标准的解决方案。

当前.exe的路径


#include <Windows.h>

std::wstring getexepathW()
{
    wchar_t result[MAX_PATH];
    return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));
}

std::wcout << getexepathW() << std::endl;

//  -------- OR --------

std::string getexepathA()
{
    char result[MAX_PATH];
    return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));
}

std::cout << getexepathA() << std::endl;