Reputation: 11
I'd like to open a file, but there is three cases which can happen:
I know about checking NULL
pointer:
FILE *f = fopen(fname, "r");
if (f == NULL) {
//
}
But I also know about access()
:
if (access(fname, F_OK|R_OK) != 0) {
//
}
I tried to remove the permission checking for the file and use only the checking of NULL
pointer. It works for every case.
What is the difference between using access()
with F_OK|R_OK
and checking NULL
pointer?
If we won't give an advantage to checking NULL
pointer, because of checking memory limit.
Upvotes: 1
Views: 1292
Reputation: 5201
When you need to reliably check the access to a file before opening it, you face the famous TOCTOU problem. So, any solution which consists to use some sort of "atomic" operation is preferable. So, calling (f)open() and then check the errors if any would be better than calling access() followed by a (f)open() call.
Upvotes: 0
Reputation: 180058
What is difference between using access() with F_OK|R_OK and checking NULL pointer?
The two are not really comparable. Even if you perform a successful test with access()
first, you still need a null check for the fopen()
, and if that fails, you still don't know for sure why without checking errno
. On the other hand, if you first perform an unsuccessful test with access()
, that doesn't tell you with certainty that a subsequent fopen()
will fail. Failure of access()
and failure of fopen()
tell you different things.
Part of the issue here is that computing systems are dynamic. For example, just because a file is absent or inaccessible to me now does not mean that it will not be created or made accessible at some point between now and now + t, even for very small t. If your intention is to open the file if that is possible, then the best approach is to go straight to attempting to open it. It's important to check whether that succeeds, but it is usually pretty unimportant to programmatically evaluate the reason for any failure. perror()
and sys_errlist
provide means to generate appropriate user feedback.
Upvotes: 1