Or Smith
Or Smith

Reputation: 3596

How do I know why stat failed?

I want to know if file is exists with C.

I saw that I can do it by this function:

int file_exist (char *filename)
{
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

But stat can failed also if the file exists, but there were some other errors (and then I would get negative number). How I know that stat fail because the file doesn't exists?

Upvotes: 1

Views: 1579

Answers (1)

elyashiv
elyashiv

Reputation: 3691

At least in UNIX systems there is a var called errno that gets the exact error you got. Check it against EFAULT. (more details on man 2 stat and man errno).

Checking is something like this:

if (stat(path) == -1)
    if (errno == EFAULT)
        //file does not exist
    else
        //some other error occurred 

Upvotes: 4

Related Questions