首页 文章

fopen返回null,perror打印无效参数

提问于
浏览
0

我创建了一个名为“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”错误消息?

2 回答

  • 2

    看看man fopen

    EINVAL提供给fopen(),fdopen()或freopen()的模式无效 .

    可能 test.txt 不可读 .

  • 1

    尝试使用-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" . 它还返回一个整数值,如果该文件不存在,则该值为非零 .

相关问题