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

时间:2014-11-04 12:21:02

标签: c fopen file-handling

我创建了一个名为" 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什么时候返回&#34;无效的参数&#34;错误消息?

2 个答案:

答案 0 :(得分:2)

查看man fopen

  

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

可能test.txt无法读取。

答案 1 :(得分: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中存储了很多关于文件的信息(例如长度,类型等),在这种情况下命名为&#34; s&#34;。它还返回一个整数值,如果该文件不存在,则该值不为零。

相关问题