getcwd() 对比 get_current_dir_name()?

getcwd() vs get_current_dir_name()?

getcwd(NULL, 0)好还是get_current_dir_name()好?常见做法是什么?

我不知情的猜测是调用 getcwd(NULL, 0) 可能是一个更好的主意,因为可能未设置 PWD 变量...

Is it better to use getcwd(NULL, 0) or get_current_dir_name() ? What is common practice ?

这是特定于操作系统的。我猜你使用 Linux.

然后,阅读syscalls(2) and getcwd(3). Study the source code of its implementation in GNU libc or in musl libc

注意

  • getcwd 采用给定已知大小的缓冲区。实际上,256 字节通常就足够了,但原则上缓冲区应该大得多。参见 sysconf(3) and pathconf(3). Accepting getcwd(NULL,0) is an extension equivalent to get_current_dir_name() so uses malloc and could fail. My Debian computer has in /usr/include/linux/limits.h a macro definition #define PATH_MAX 4096 (but 4096, when used as the size of some automatic variable, is a lot for a call frame of any recursive function; look also into nftw(3))。

  • getwd 已过时,因为容易出现缓冲区溢出。 2021年不要用了。

  • get_current_dir_name 使用 malloc(3) 可能会失败。

AFAIK,getcwd(3) 不应使用 PWD 环境变量。如果您使用它

编写自己的 /sbin/init 代码,它应该可以工作

有时,您可以引导 Linux 内核 运行ning /bin/bash 而不是 /sbin/init。在这种情况下,未设置 PWD 环境变量。参见 environ(7) and credentials(7)

当然,在大多数其他程序中,PWD 已正确设置(例如 GNU bash, whose source code you can study since it is free software

个人推荐

  • 假设并记录您的程序不会 运行 文件路径大于例如256 字节(但请注意下面的 pathUTF 8 is everywhere in 2021). This assumption could be false for file names which are generated with UUID strings or several IPV6 addresses, and you might want to use C dynamic memory allocation.... 所以几乎等同于 get_current_dir_name。不要忘记 free 它!

  • 代码如下:

    char path[256];
    memset (path, 0, sizeof(path));
    if (getcwd(path, sizeof(path)) == NULL) {
      perror("getcwd");
      exit(EXIT_FAILURE); // or abort()
    }
    

当然,如果您为某些机器人编写类似 init 的程序,这还不够好。火星上的机器人可能 生成 长路径名!