wackyTechie
wackyTechie

Reputation: 113

fopen returns null and perror prints invalid argument

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?

Upvotes: 0

Views: 2601

Answers (2)

Gophyr
Gophyr

Reputation: 406

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.

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136495

Have a look at man fopen:

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

Probably test.txt is not readable.

Upvotes: 2

Related Questions