【问题标题】:Opening a file using relative path on Linux in C在 C 中使用 Linux 上的相对路径打开文件
【发布时间】:2021-02-12 15:35:52
【问题描述】:

我是 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");

我在这里做错了什么?

【问题讨论】:

  • 只有当您位于正确的 c当前文件夹中时,相对路径才有效
  • 运行程序时的当前目录是什么?程序是否会更改目录?相对路径的基本位置与源代码的位置无关;唯一重要的是进程的当前工作目录。
  • IOW,尝试类似:const char *path = "dataset/data.txt"; if( (stream = fopen(path, "r")) == NULL ){ perror(path); printf("current dir: %s\n", getcwd(NULL, 0); exit(1); }
  • @WilliamPursell 我现在明白了。我正在使用 CLion。构建后的最终可执行文件位于./cmake-build-debug 目录中。所以我使用了../dataset/data.txt,它奏效了。谢谢!

标签: c linux file


【解决方案1】:

阅读path_resolution(7)。

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

当fopen 失败(或某些syscalls(2) 失败)时,使用errno(3) 或perror(3)。

注意glob(3)、getcwd(2) 和fnmatch(3)。

另见proc(5)。

【讨论】:

    猜你喜欢
    • 2017-09-05
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2011-02-25
    • 2018-11-30
    • 2016-06-24
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多