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 .
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.
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.
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.
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.
Edit: forgot to wrap fclose into a else
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#).