C 语言中获取当前工作目录
    
    Jinku Hu
    2023年10月12日
    
    C
    C Directory
    
 
本文将介绍几种在 C 语言中获取当前工作目录的方法。
使用 getcwd 函数获取当前工作目录的方法
    
getcwd 函数是一个符合 POSIX 标准的系统调用,可以检索调用程序的当前工作目录。getcwd 需要两个参数 - char* 缓冲区,其中存储路径名,以及给定缓冲区中分配的字节数。该函数将当前工作目录的名称存储为一个空头字符串,用户有责任保证 char* 地址有足够的空间来存储路径名。注意,getcwd 返回的是目录的绝对路径名。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef MAX_BUF
#define MAX_BUF 200
#endif
int main(void) {
  char path[MAX_BUF];
  getcwd(path, MAX_BUF);
  printf("Current working directory: %s\n", path);
  exit(EXIT_SUCCESS);
}
在 C 语言中正确验证 getcwd 函数返回的值以获取当前工作目录
getcwd 函数可能无法检索到正确的值;因此,在这种情况下,它返回 NULL,并设置 errno 与相应的错误代码。用户负责实现错误检查代码,并根据需要修改程序的控制流程,以适应特定情况。需要注意的是,我们在调用 getcwd 函数之前将 errno 显式地设置为零,因为最好的做法是在调用到答应设置 errno 的库函数之前设置。如果 size 参数小于工作目录的路径名,errno 会被设置为 ERANGE。
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef MAX_BUF
#define MAX_BUF 200
#endif
int main(void) {
  char path[MAX_BUF];
  errno = 0;
  if (getcwd(path, MAX_BUF) == NULL) {
    if (errno == ERANGE)
      printf("[ERROR] pathname length exceeds the buffer size\n");
    else
      perror("getcwd");
    exit(EXIT_FAILURE);
  }
  printf("Current working directory: %s\n", path);
  exit(EXIT_SUCCESS);
}
另外,我们也可以将 NULL 值作为第一个参数传递给 getcwd 函数,0 作为第二个参数。函数本身会使用 malloc 动态分配一个足够大的缓冲区,并返回指向该位置的 char 指针。注意,用户应该在返回的指针上调用 free 函数来重新分配缓冲区内存。
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef MAX_BUF
#define MAX_BUF 200
#endif
int main(void) {
  char path[MAX_BUF];
  errno = 0;
  char *buf = getcwd(NULL, 0);
  if (buf == NULL) {
    perror("getcwd");
    exit(EXIT_FAILURE);
  }
  printf("Current working directory: %s\n", buf);
  free(buf);
  exit(EXIT_SUCCESS);
}
使用 get_current_dir_name 函数获取当前工作目录
get_current_dir_name 是另一个可以检索当前工作目录的函数。注意这个函数需要定义 _GNU_SOURCE 宏,否则代码很可能会出现编译错误。get_current_dir_name 不接受参数,返回 char 指针,类似于 getcwd 函数。内存是用 malloc 自动分配的,调用者的代码负责释放返回的指针。
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef MAX_BUF
#define MAX_BUF 200
#endif
int main(void) {
  char path[MAX_BUF];
  errno = 0;
  char *buf = get_current_dir_name();
  if (buf == NULL) {
    perror("get_current_dir_name");
    exit(EXIT_FAILURE);
  }
  printf("Current working directory: %s\n", buf);
  free(buf);
  exit(EXIT_SUCCESS);
}
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
