我正在做一个C程序,我需要得到程序开始的目录。这个程序是为UNIX计算机编写的。我一直在看opendir()和telldir(),但telldir()返回一个off_t(长int),所以它真的没有帮助我。

我如何能得到当前路径在一个字符串(字符数组)?


当前回答

查看getcwd的手册页。

其他回答

查看getcwd的手册页。

你有看过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;
}

虽然问题被标记为Unix,但当人们的目标平台是Windows时,也可以访问它,Windows的答案是GetCurrentDirectory()函数:

DWORD WINAPI GetCurrentDirectory(
  _In_  DWORD  nBufferLength,
  _Out_ LPTSTR lpBuffer
);

这些答案适用于C和c++代码。

user4581301在另一个问题的评论中建议的链接,并通过谷歌搜索“site:microsoft.com getcurrentdirectory”验证为当前的首选。

注意,getcwd(3)也可以在Microsoft的libc: getcwd(3)中使用,其工作方式与您预期的相同。

必须与-loldnames (oldnames。Lib,在大多数情况下自动完成),或使用_getcwd()。没有前缀的版本在Windows RT下不可用。

#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;
}