我正在编写一个C程序,其中我需要获取启动该程序的目录。这个程序是为UNIX计算机编写的。我一直在寻找opendir()
和telldir()
,但是telldir()
返回了一个off_t (long int)
,所以它对我没有什么帮助。
如何获取字符串(char数组)中的当前路径?
发布于 2008-11-18 19:38:25
你看过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;
}
发布于 2008-11-18 11:37:30
查找getcwd
的手册页。
发布于 2017-12-19 06:39:40
#include <stdio.h> /* defines FILENAME_MAX */
//#define WINDOWS /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
int main(){
char buff[FILENAME_MAX];
GetCurrentDir( buff, FILENAME_MAX );
printf("Current working dir: %s\n", buff);
return 1;
}
https://stackoverflow.com/questions/298510
复制相似问题