Is there a better way than simply trying to open the file?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, \"r\")))
{
Look up the access()
function, found in unistd.h
. You can replace your function with
if( access( fname, F_OK ) != -1 ) {
// file exists
} else {
// file doesn't exist
}
You can also use R_OK
, W_OK
, and X_OK
in place of F_OK
to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK
)
Update: Note that on Windows, you can't use W_OK
to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK )
may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
You can use realpath() function.
resolved_file = realpath(file_path, NULL);
if (!resolved_keyfile) {
/*File dosn't exists*/
perror(keyfile);
return -1;
}
Use stat
like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
I can't remember where I got this from that I used in my assignment (I usually copy paste the URL where I found it as an easy form of citation) and I cannot decipher what the trailing (file) = 0
is although my best guess is that it is redundancy to set any references to file to 0.
#define fclose(file) ((file) ? fclose(file) : 0, (file) = 0)
file
if a pointer declared as:
FILE *file=NULL;
Yes. Use stat()
. See the man page forstat(2).
stat()
will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).
Oh, as someone else mentioned, you can also use access()
. However I prefer stat()
, as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).
FILE *file;
if((file = fopen("sample.txt","r"))!=NULL)
{
// file exists
fclose(file);
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
}