Reputation: 12516
I apologize for my bad English.
Different files can has different permissions. For example I can have not permission for a file read/write, but this file is exists. How can I check existence of the such file via C89?
Thank you. Best Regards
Upvotes: 1
Views: 172
Reputation: 23737
There is no portable way to determine wheter a file exists; you have to resort to a system-specific method (such as access
or stat
from POSIX.1). Sometimes, it may not be possible to check the existence of a named file, because you don't have permission to read the directory that may contain it.
Upvotes: 2
Reputation:
In pure ISO C89, there's no good and portable way of checking the existence of a file. However, there are implementation-defined solutions or other OS-specific extensions for that. For example:
int file_exists(const char *name)
{
return access(name, F_OK) == 0;
}
Note that this (access()
) is not part of C89, but most systems one cares about have it.
Or there is
int file_exists(const char *name)
{
FILE *f = fopen(name, "r");
if ((f == NULL) && (errno == ENOENT)) {
return 0;
}
fclose(f);
return 1;
}
This is again not C89, but most C89-conformant systems will provide ENOENT
.
Another option is to use the stat()
function, it also returns -1 and sets errno
to ENOENT
if the file doesn't exist.
Upvotes: 3
Reputation: 62106
If you stick to C89, there's no universal way of checking for file existence.
There are some standard functions outside of C89, POSIX functions:
At any rate, it depends on the OS since the language itself does not provide such functionality.
Upvotes: 2