【问题标题】:fopen returns null and perror prints invalid argumentfopen 返回 null 并且 perror 打印无效参数
【发布时间】:2014-11-04 12:21:01
【问题描述】:

我创建了一个名为“test”的文件,但我无法使用 fopen 打开它。 这是代码-

#include<stdio.h>
int main()
{
    FILE *fp;
    fp=fopen("test.txt","r");
    if(fp==NULL)
    {
        perror("Error: ");
    }
    fclose(fp);
    return 0;
}

当我运行上面的代码时,我得到以下输出:

Error: Invalid argument

可能是什么原因? perror 什么时候返回“Invalid argument”错误信息?

【问题讨论】:

  • 在哪个操作系统上?如果在 Linux 上,您可以使用 strace(1) 来了解实际情况......
  • 对我来说很好用!也不要忘记包含#include &lt;stdio.h&gt; 否则FILE 类型未知
  • 检查文件扩展名(.txt)是否与程序中的相同
  • 在 Windows 上,不能有多个进程同时读取和写入同一个文件。

标签: c fopen file-handling


【解决方案1】:

看看man fopen:

EINVAL 提供给 fopen()、fdopen() 或 freopen() 的模式无效。

可能test.txt 不可读。

【讨论】:

  • 但是"r"是一个有效的模式。
  • 据我了解,fopen(3) 和 open(2),errno 在特定情况下应该是 EACCESS,至少在 Posix 上。
【解决方案2】:

尝试使用 -g 编译。这让您可以使用 gdb 逐步调试程序;查找如何使用它。执行此操作的更好方法可能是使用 stat(2)。这是一个代码示例,如果文件不存在或不是常规文件,将返回错误:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
  struct stat s;

  int check = stat("test.txt", &s);
  if(check != 0){
    printf("ERROR: File does not exist!\n");

    return -1;
  }

  return 0;
}

Stat 在struct stat 中存储了很多关于文件的信息(例如长度、类型等),在这种情况下被命名为“s”。它还返回一个整数值,如果文件不存在,则该值非零。

【讨论】:

  • 如果你先在stat 后面跟着open,那么当文件系统内容可能发生变化时,这两个调用之间会有一个很小的时间窗口。正确的方法是做open 和失败检查errno。
  • 有一件事我忘了说:我认为 stat 只存在于 POSIX 系统上,而不是 Windows 等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
相关资源
最近更新 更多