首页 > 解决方案 > 在 C 中使用 Linux 上的相对路径打开文件

问题描述

我是 C 编程的新手。我有以下目录结构。

Project
   |____ dataset
   |        |_____ data.txt
   |
   |____ main.c

我的代码:

FILE *stream = fopen("dataset/data.txt", "r");

或者

FILE *stream = fopen("./dataset/data.txt", "r");

返回此错误:No such file or directory

但是当我使用绝对路径时,它可以正常工作:

FILE *stream = fopen("/home/<user_name>/C/<project_name>/dataset/data.txt", "r");

我在这里做错了什么?

标签: clinuxfile

解决方案


阅读path_resolution(7)

您可能想要使用chdir(2),因为fopen(3)调用open(2)并且所有这些都可能失败。

fopen失败(或某些 系统调用(2)失败)时,使用errno(3)perror(3)

请注意glob(3)getcwd(2)fnmatch(3)

另请参见proc(5)


推荐阅读