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

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

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


慕桂英546537
浏览 983回答 4
4回答

陪伴而非守候

你看过了getcwd()吗?#include <unistd.h>char *getcwd(char *buf, size_t size);简单的例子:#include <unistd.h>#include <stdio.h>#include <limits.h>int main() {&nbsp; &nbsp;char cwd[PATH_MAX];&nbsp; &nbsp;if (getcwd(cwd, sizeof(cwd)) != NULL) {&nbsp; &nbsp; &nbsp; &nbsp;printf("Current working dir: %s\n", cwd);&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp;perror("getcwd() error");&nbsp; &nbsp; &nbsp; &nbsp;return 1;&nbsp; &nbsp;}&nbsp; &nbsp;return 0;}

长风秋雁

查找手册页getcwd。

潇潇雨雨

#include <stdio.h>&nbsp; /* defines FILENAME_MAX *///#define WINDOWS&nbsp; /* uncomment this line to use it for windows.*/#ifdef WINDOWS#include <direct.h>#define GetCurrentDir _getcwd#else#include <unistd.h>#define GetCurrentDir getcwd#endifint main(){&nbsp; char buff[FILENAME_MAX];&nbsp; GetCurrentDir( buff, FILENAME_MAX );&nbsp; printf("Current working dir: %s\n", buff);&nbsp; return 1;}
打开App,查看更多内容
随时随地看视频慕课网APP