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

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


当前回答

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

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

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

在我的程序中,我想知道程序是否 从用户的bin目录或路径中的其他目录执行 或者从/usr/bin。/usr/bin将包含受支持的版本。 我的感觉是在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 );
}

文件系统TS现在是一个标准(gcc 5.3+和clang 3.9+都支持),所以你可以使用它的current_path()函数:

std::string path = std::experimental::filesystem::current_path();

在gcc(5.3+)包含文件系统,你需要使用:

#include <experimental/filesystem>

用-lstdc++fs标记链接你的代码。

如果你想在Microsoft Visual Studio中使用文件系统,请阅读本文。

只是我的两美分,但下面的代码在c++ 17中不能移植吗?

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[])
{
    std::cout << "Path is " << fs::path(argv[0]).parent_path() << '\n';
}

至少在Linux上对我有用。

根据前面的想法,我现在有:

std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = "");

与实现:

fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)
{
    static auto exe_parent_path = fs::path(exe_path).parent_path();
    return exe_parent_path / filename;
}

main()中的初始化技巧:

(void) prepend_exe_path("", argv[0]);

感谢@Sam Redway的argv[0]想法。当然,我知道当OP提出这个问题时,c++ 17还没有出现很多年。

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

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

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

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

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

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

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