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

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


当前回答

在stdlib.h中像这样使用realpath():

char *working_dir_path = realpath(".", NULL);

其他回答

Boost Filesystem的initial_path()的行为类似于POSIX的getcwd(),它们本身都不能满足您的需要,但是将argv[0]附加到它们中的任何一个都可以做到这一点。

您可能会注意到,结果并不总是很漂亮——您可能会得到/foo/bar/../ baz/a这样的东西。Out或/foo/bar//baz/a。out,但我相信它总是会产生一个有效的路径,该路径命名可执行文件(注意,路径中连续的斜杠被折叠为一个)。

我以前用envp (main()的第三个参数)写了一个解决方案,它在Linux上有效,但在Windows上似乎行不通,所以我基本上是在推荐和其他人以前一样的解决方案,但附加了为什么它实际上是正确的,即使结果并不漂亮。

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

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);

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

#include <filesystem>

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

更多信息请参见cppreference.com。

下面是获取执行应用程序的完整路径的代码:

变量声明:

char pBuf[256];
size_t len = sizeof(pBuf); 

窗口:

int bytes = GetModuleFileName(NULL, pBuf, len);
return bytes ? bytes : -1;

Linux:

int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if(bytes >= 0)
    pBuf[bytes] = '\0';
return bytes;