襄阳古隆中游玩攻略:c语言中如何得到当前文件所在位置

来源:百度文库 编辑:高考问答 时间:2024/05/05 09:16:54
打开一个gethodh.c的文件,想获取此文件所在的完全路径,就是所在的位置,怎样实现呢?

如果是通过open方式打开的,那么第一个参数就是文件路径信息:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *path, int oflag, /* mode_t mode */...);

如果是通过fopen方式打开的,那么第一个参数就是文件路径信息:
#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);

无论通过open还是fopen打开文件,都必须先知道文件路径信息,尽管可能是相对路径。
如果知道了filename的内容,我们就可以定位它的绝对路径,也就是你说的完全路径。

1. filename本身就是绝对路径,ok。
2. filename是相对路径,那么先通过getcwd获取进程的执行路径,然后再获取绝对路径即可。
#include <unistd.h>
extern char *getcwd(char *buf, size_t size);

但是,如果进程在打开文件后又执行了chdir、fchdir之类函数的话,估计就不能够再获取文件路径信息了。
#include <unistd.h>
int chdir(const char *path);
int fchdir(int fildes);