fopen returns null and perror prints invalid argument

↘锁芯ラ 提交于 2019-12-12 02:55:17

问题


I created a file named "test" but I'm unable to open it using fopen. Here is the code-

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

When I run the above code, I get the following output:

Error: Invalid argument

What could be the reason? When does perror return "Invalid argument" error message?


回答1:


Have a look at man fopen:

EINVAL The mode provided to fopen(), fdopen(), or freopen() was invalid.

Probably test.txt is not readable.




回答2:


Try compiling with -g. This lets you use gdb to debug the program step by step; look up how to use it. Probably a better way of doing this is with stat(2). Here is a sample of code that will return an error if the file does not exist, or is not a regular file:

#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 stores a lot of information about a file (such as lenght, type, etc.) in the struct stat, which in this case is named "s". It also returns an integer value, which is non-zero if the file does not exist.



来源:https://stackoverflow.com/questions/26735029/fopen-returns-null-and-perror-prints-invalid-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!