如何获得在C程序的当前目录? [英] How to get the current directory in a C program?
本文介绍了如何获得在C程序的当前目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个C程序中我需要得到该程序启动的目录。这一方案是对UNIX计算机编写的。我一直在看执行opendir()
和 telldir()
,但 telldir()
返回 off_t(长整型)
,所以它真的不帮助我。
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)?
推荐答案
你吃过一看<一个href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html\"><$c$c>getcwd()$c$c>?
#include <unistd.h>
char *getcwd(char *buf, size_t size);
简单的例子:
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL)
fprintf(stdout, "Current working dir: %s\n", cwd);
else
perror("getcwd() error");
return 0;
}
这篇关于如何获得在C程序的当前目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文