【问题标题】:Can not read from opened file无法从打开的文件中读取
【发布时间】:2015-02-09 14:38:55
【问题描述】:

该文件存在,我刚刚在另一个函数中读取它。另一个函数关闭文件。现在,我的workwith() 尝试打开它并从中读取。

我的代码:

if (access(path_file, F_OK) != -1) {
  // file exists
  *mfs_desc = open(path_file, O_WRONLY | O_RDONLY, 0600);
  if (*mfs_desc == -1) {
    perror("opening file");
    exit(1);
  }
  printf("file_descriptor = %d, filename = |%s|\n", *mfs_desc,
         path_file);
  if ((read(*mfs_desc, superblock, sizeof(Superblock))) == - 1) {
    perror("read superblock");
    exit(1);
  }
}

但是,我得到了这个输出:

file_descriptor = 3, filename = |t.mfs|
read superblock: Bad file descriptor

我怀疑我打开文件的方式不正确。我想打开文件以进行读写。该文件已经存在。我错过了什么?

【问题讨论】:

    标签: c linux file io posix


    【解决方案1】:

    更改此标志

    O_WRONLY | O_RDONLY
    

    到

    O_RDWR
    

    检查here,它表示标志必须包含一种访问模式。

    此外,参考文献提到:

    参数标志必须包括以下访问模式之一: O_RDONLY、O_WRONLY 或 O_RDWR。这些请求打开文件读取- only、只写或读/写。

    【讨论】:

    • 他们不能很好地在一起|,因为最初的“模式”只是一个布尔值,表明你是否想要写访问权。读写模式不存在。添加时,为了兼容性,readonly 的数值保持为 0。 V3 man page V4 man page ... 我认为 Ken 和 Dennis 足够聪明,他们知道 O_RDWR != O_RDONLY|O_WRONLY 很愚蠢,如果可以的话,会修复它。
    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 2011-11-19
    • 2016-11-11
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多