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

xoefb8l8  于 5个月前  发布在  Unix
关注(0)|答案(7)|浏览(81)

我正在做一个C程序,我需要从那里获取程序的启动目录。这个程序是为UNIX计算机编写的。我一直在看opendir()telldir(),但是telldir()返回off_t (long int),所以它真的帮不上我。
如何在字符串(char数组)中获取当前路径?

wkftcu5l

wkftcu5l1#

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

9o685dep

9o685dep2#

查看getcwd的手册页。

bprjcwpo

bprjcwpo3#

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

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

字符串
这些答案适用于C和C++代码。
user4581301在评论中建议链接到另一个问题,并通过Google搜索“site:microsoft.com getcurrentdirectory”验证为当前首选。

ndh0cuux

ndh0cuux4#

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

字符串

cqoc49vn

cqoc49vn5#

要获取当前目录(执行目标程序的目录),可以使用以下示例代码,该代码适用于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;
}

字符串

uurv41yg

uurv41yg6#

请注意,getcwd(3)也可以在Microsoft的libc:getcwd(3)中使用,其工作方式与您预期的相同。
必须使用-loldnames(旧名称.lib,在大多数情况下自动完成)链接,或使用_getcwd()。无前缀版本在Windows RT下不可用。

oyxsuwqo

oyxsuwqo7#

使用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;
}

字符串

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

相关问题