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

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


当前回答

If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from the directory that holds the current executable program file. It isn't necessarily the same directory; if someone runs the program from a command prompt, then the program is being run from the command prompt's current working directory even though the program file lives elsewhere.

getcwd是一个POSIX函数,所有POSIX兼容平台都支持它。你不需要做任何特殊的事情(除了在Unix上包含正确的头文件unistd.h和在windows上包含direct.h)。

由于您正在创建一个C程序,它将链接到默认的C运行时库,该库由系统中的所有进程链接(避免特别设计的异常),默认情况下它将包含这个函数。CRT从来不被认为是一个外部库,因为它为操作系统提供了基本的标准兼容接口。

在windows上,getcwd函数已弃用,而支持_getcwd。我觉得你可以这样用。

#include <stdio.h>  /* defines FILENAME_MAX */
#ifdef WINDOWS
    #include <direct.h>
    #define GetCurrentDir _getcwd
#else
    #include <unistd.h>
    #define GetCurrentDir getcwd
 #endif

 char cCurrentPath[FILENAME_MAX];

 if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
     {
     return errno;
     }

cCurrentPath[sizeof(cCurrentPath) - 1] = '\0'; /* not really required */

printf ("The current working directory is %s", cCurrentPath);

其他回答

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

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

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

不,没有标准的方法。我相信C/ c++标准甚至没有考虑目录(或其他文件系统组织)的存在。

在Windows上,当hModule参数设置为NULL时,GetModuleFileName()将返回当前进程可执行文件的完整路径。Linux我帮不上忙。

此外,您还应该明确您想要的是当前目录还是程序映像/可执行文件所在的目录。就目前情况来看,你的问题在这一点上有点模棱两可。

我知道现在回答这个问题已经很晚了,但我发现没有一个答案像我自己的解决方案那样对我有用。一个非常简单的方法来获取路径从你的CWD到你的bin文件夹是这样的:

int main(int argc, char* argv[])
{
    std::string argv_str(argv[0]);
    std::string base = argv_str.substr(0, argv_str.find_last_of("/"));
}

您现在可以使用它作为相对路径的基。例如,我有这样的目录结构:

main
  ----> test
  ----> src
  ----> bin

我想把我的源代码编译到bin并写一个日志来测试,我可以把这一行添加到我的代码中。

std::string pathToWrite = base + "/../test/test.log";

我在Linux上尝试过这种方法,使用全路径,别名等,它工作得很好。

注意:

如果你是在windows中,你应该使用“\”作为文件分隔符,而不是“/”。你也需要转义这个,例如:

std::string base = argv[0].substr(0, argv[0].find_last_of("\\"));

我认为这应该工作,但还没有测试,所以评论将是感激如果它工作或修复如果不是。

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

例子:

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

一个库解决方案(尽管我知道这不是要求的)。 如果你恰好使用Qt: QCoreApplication: applicationDirPath ()