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

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


当前回答

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

其他回答

linux bash命令 哪个progname将报告程序的路径。

即使可以在程序中发出which命令,并将输出定向到tmp文件和程序 随后读取TMP文件,它不会告诉您该程序是否是正在执行的程序。它只告诉您具有此名称的程序位于何处。

所需要的是获取进程id号,并解析出该名称的路径

在我的程序中,我想知道程序是否 从用户的bin目录或路径中的其他目录执行 或者从/usr/bin。/usr/bin将包含受支持的版本。 我的感觉是在Linux中有一个可移植的解决方案。

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

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

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

从c++ 11开始,使用实验文件系统,c++ 14- c++ 17以及使用正式文件系统。

application.h:

#pragma once

//
// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
//
#ifdef __cpp_lib_filesystem
#include <filesystem>
#else
#include <experimental/filesystem>

namespace std {
    namespace filesystem = experimental::filesystem;
}
#endif

std::filesystem::path getexepath();

application.cpp:

#include "application.h"
#ifdef _WIN32
#include <windows.h>    //GetModuleFileNameW
#else
#include <limits.h>
#include <unistd.h>     //readlink
#endif

std::filesystem::path getexepath()
{
#ifdef _WIN32
    wchar_t path[MAX_PATH] = { 0 };
    GetModuleFileNameW(NULL, path, MAX_PATH);
    return path;
#else
    char result[PATH_MAX];
    ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
    return std::string(result, (count > 0) ? count : 0);
#endif
}

这是来自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 );
}

你不能为此目的使用argv[0],通常它包含可执行文件的完整路径,但也不是必须的——进程可以在字段中使用任意值创建。

还要注意,当前目录和可执行文件所在的目录是两个不同的东西,所以getcwd()也帮不了你。

Windows上使用GetModuleFileName(), Linux上读取/dev/proc/procID/..文件。