gpt4 book ai didi

c - 如何在C程序中获取当前目录?

转载 作者:太空狗 更新时间:2023-10-29 16:14:15 28 4
gpt4 key购买 nike

我正在制作一个 C 程序,我需要在其中获取程序的启动目录。这个程序是为 UNIX 计算机编写的。我一直在查看 opendir()telldir(),但是 telldir() 返回一个 off_t (long int),所以它真的对我没有帮助。

如何获取字符串(字符数组)中的当前路径?

最佳答案

你看过getcwd()了吗? ?

#include <unistd.h>
char *getcwd(char *buf, size_t size);

简单的例子:

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

int main() {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
} else {
perror("getcwd() error");
return 1;
}
return 0;
}

关于c - 如何在C程序中获取当前目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/298510/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com