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 .
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
It's impossible to check existence for certain in pure ISO standard C.
There's no really good portable way to determine whether a named file
exists; you'll probably have to resort to system-specific methods.
This isn't a portable thing, so I'll give you OS-specific calls.
In Windows you use GetFileAttributes
and check for a -1 return (INVALID_HANDLE
or something like that).
In Linux, you have fstat
to do this.
Most of the time however, I just do the file opening trick to test, or just go ahead and use the file and check for exceptions (C++/C#).
I guess this has more to do with system environment (such as POSIX or BSD) than with which version of C language you're using.
In POSIX there is a stat() syscall that will give you information about a file, even if you cannot read it. However, if the file is in path that you have no access permissions to it's always going to fail regardless of whether the file exists.
If you have no access to the path then it should never be possible to look on files contained.
Do you really want to access the file? A check is usually better with the
access(filename,F_OK)==0 from unistd.h and is pretty wide standard I think.