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

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


当前回答

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

其他回答

要获得当前目录(你执行目标程序的地方),你可以使用以下示例代码,它适用于Visual Studio和Linux/MacOS(gcc/clang),适用于C和c++:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if defined(_MSC_VER)
#include <direct.h>
#define getcwd _getcwd
#elif defined(__GNUC__)
#include <unistd.h>
#endif

int main() {
    char* buffer;

    if( (buffer=getcwd(NULL, 0)) == NULL) {
        perror("failed to get current directory\n");
    } else {
        printf("%s \nLength: %zu\n", buffer, strlen(buffer));
        free(buffer);
    }

    return 0;
}

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

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

查看getcwd的手册页。

使用getcwd

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

OR

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

main() {
char *buf;
buf=(char *)malloc(100*sizeof(char));
getcwd(buf,100);
printf("\n %s \n",buf);
}

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

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

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

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