C语言文件路径设置

C语言文件路径设置,第1张

C语言中指定文件路径的三种方法:

方法一:当前工程下的文件

fopen("demo.txt","rt")

方法二:当前工程下的 test文件夹 中文件

fopen(".\\test\\demo.txt","rt")

方法三:绝对路径,D盘下project文件夹中的文件

fopen("d:\\project\\demo.txt","rt")

如果是通过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)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11642289.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存