如何在C程序中获取当前目录? [英] How to get the current directory in a C program?

查看:22
本文介绍了如何在C程序中获取当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个 C 程序,我需要在其中获取程序启动的目录.该程序是为 UNIX 计算机编写的.我一直在查看 opendir()telldir(),但是 telldir() 返回一个 off_t (long int),所以它真的对我没有帮助.

I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at opendir() and telldir(), but telldir() returns a off_t (long int), so it really doesn't help me.

如何获取字符串(字符数组)中的当前路径?

How can I get the current path in a string (char array)?

推荐答案

你看过 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
", cwd);
   } else {
       perror("getcwd() error");
       return 1;
   }
   return 0;
}

这篇关于如何在C程序中获取当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆