Kenneth Brody said:
Joachim said:
Kenneth Brody said:
Joachim Schmitz wrote: [... use fstat() to check for file existence ...]
Well, if you have a file handle to pass to fstat(), I think we can
pretty much agree that the file exists. (Even if POSIX is OT here.)
Oops...
And, if I recall, a discussion in the past noted that a failed access()
call doesn't necessarily mean the file doesn't exist. (For example,
you may simply not have permission to check for the existence.) Also,
Very true, so you would have to check errno in case access() returns
a -1.
printf("%s does%s exist\n", filename, ((access(filename) == -1) &&
(errno==
ENOFILE))? "n't":"");
ENOENT, not ENOFILE
(I'm not sure why we're discussing POSIX here, but...)
Because ANSI/ISO C doesn't have fstat(), so the thread was OT from it's very
beginning
What if the file doesn't exist in a directory to which you do not
have the proper permissions? I believe the error will be EPERM
(or, at least, not ENOFILE), and you will display "does exist".
The point is, an error other than ENOFILE does not imply that the
file does exist. I believe the same holds true for stat() et al.
OK, make it this then:
printf("%s %s exist\n", filename, ((access(filename) == -1) && (errno==
ENOENT))? "doesn't":"may");
The only thing you can reliably check for is whether you can open
the file, by seeing what fopen() returns. (Yes, you can use
something like access() to see if you have permission to a file
_at_the_time_you_call_access()_, but you have race conditions to
take into account.)
The OP was looking for an alternative to fstat() to check for the existence
of a file, that request seems entirly unneccessary, as fstat() requires the
file to have been open()ed first, hence proving that it exists and is
accessible.
To bring it back to topicallity, how about this:
#include <stdio.h>
#include <errno.h>
/*
* return 1 if file could be opened, proving it's existence, 0 otherwise,
* which is not a secure sign that the file doesn't exist!
*/
int faccess(char *filename)
{
FILE *fp;
/* mode got to be "r" or "r+", anything else would create it */
fp=fopen(filename, "r");
if (fp)
fclose(fp);
return fp?1:0;
}
/*
* returns 0 if filename does not exist, 1 if it exists and -1 if unsure
* i.e. if couldn't be opened for reading, but this could be due to
permissions
* to the file or some component of the file's path
*/
int fexist(char *filename)
{
errno=0;
(void)faccess(filename);
perror("");
switch (errno)
{
case 0: return 1;
case ENOENT: return 0;
default: return -1;
}
}
Bye, Jojo