Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C check if file exists

Tags:

c

c89

In a project I have to do in C89 standard I have to check if a file exists. How do I do this?

I thought of using

FILE *file;
if ((file = fopen(fname, "r")) == NULL)
{
  printf("file doesn't exists");
}
return 0;

but I think there can be more cases then file doesn't exists that will do fopen == NULL.

How do I do this? I prefer not using includes rather then .

like image 356
The GiG Avatar asked Apr 21 '11 14:04

The GiG


People also ask

How do I check if a file exists in C?

access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.

How do you check if a file is in a directory in C?

The isDir() function is used to check a given file is a directory or not.

What does fopen return if file does not exist?

If the file exists, its contents are cleared unless it is a logical file. ab. Open a binary file in append mode for writing at the end of the file. The fopen function creates the file if it does not exist.

How is fopen () used?

The fopen() function opens the file specified by filename and associates a stream with it. The mode variable is a character string specifying the type of access requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters.


1 Answers

If you can't use stat() in your environment (which is definitely the better approach), just evaluate errno. Don't forget to include errno.h.

FILE *file;
if ((file = fopen(fname, "r")) == NULL) {
  if (errno == ENOENT) {
    printf("File doesn't exist");
  } else {
    // Check for other errors too, like EACCES and EISDIR
    printf("Some other error occured");
  }
} else {
  fclose(file);
}
return 0;

Edit: forgot to wrap fclose into a else

like image 61
onitake Avatar answered Sep 22 '22 13:09

onitake