如何从C获取到Linux中当前文件(pwd)的路径? [英] How to get the to get 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 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 the file3
and I want to use system("pwd")
to get path: ..../example/test2/file3
. Is this somehow possible or pwd
will return path to the 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屋!
查看全文