如何从C获取Linux中当前文件(pwd)的路径? [英] How to get the path to the current file (pwd) in Linux from C?
本文介绍了如何从C获取Linux中当前文件(pwd)的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能在当前DIR上运行 system("pwd")
.因此,例如,我们具有以下文件夹结构:
I'd like to know if it is somehow possible to run system("pwd")
on the current DIR. So for example let's have this folder structure:
example
>test
>>file
>test2
>>file3
>>file4
然后使用 opendir()
和 readdir()
,我将进入 file3
,我想使用 system(("pwd")
以获得路径 ..../example/test2/file3
.这有可能吗,还是 pwd
始终将路径返回到 main.c
?
And with opendir()
and readdir()
I'll get to file3
, and I want to use system("pwd")
to get the path ..../example/test2/file3
. Is this somehow possible, or will pwd
return the path to main.c
all the time?
推荐答案
仅打开和读取目录不会更改当前的工作目录.但是,将在程序中更改目录.
Simply opening and reading directories does not change the current working directory. However, changing directory in your program will.
供参考,
#include <unistd.h>
#include <stdio.h>
int main() {
char cwd[1024];
chdir("/path/to/change/directory/to");
getcwd(cwd, sizeof(cwd));
printf("Current working dir: %s\n", cwd);
}
这篇关于如何从C获取Linux中当前文件(pwd)的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文