题
我正在制作一个C程序,我需要从中获取程序启动的目录。该程序是为UNIX计算机编写的。我一直在看opendir()
和telldir()
,但是off_t (long int)
会返回<=>,所以它对我没有帮助。
如何获取字符串中的当前路径(char数组)?
解决方案
您是否看过 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;
}
其他提示
查找getcwd
的手册页。
虽然问题标记为Unix,但当目标平台为Windows时,人们也会访问它,Windows的答案是 GetCurrentDirectory()
功能:
DWORD WINAPI GetCurrentDirectory(
_In_ DWORD nBufferLength,
_Out_ LPTSTR lpBuffer
);
这些答案适用于C和C ++代码。
user4581301 在评论到另一个问题,并通过Google搜索网站验证为当前首选:microsoft.com getcurrentdirectory'。
#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;
}
请注意,getcwd(3)
也可以在Microsoft的libc中找到: getcwd(3),其工作方式与预期相同。
必须与-loldnames
(oldnames.lib,在大多数情况下自动完成)或使用_getcwd()
链接。在Windows RT下,无前缀版本不可用。
不隶属于 StackOverflow