Reputation: 129
I am trying to check if my file specified by file_path
exists and is readable. This is my code:
if (stat(file_path,&fileStat) > 0 && (fileStat.st_mode & S_IRUSR))
{
puts("SUCCESS");
create_message(OK);
}
Can you detect a problem with the given code? Is the part (fileStat.st_mode & S_IRUSR)
correct?
Upvotes: 1
Views: 217
Reputation: 1301
You don't want stat() for this, you want access().
if (access(filename, R_OK)) {
// code to handle missing or unreadable file
} else {
// code to handle readable file
}
Your code would work if you changed the test on the return value of stat() as Jonathan Leffler points out, but Unix provides a system call to do precisely what you want, so you might as well use it.
But as other commenters have pointed out, if you are going to read this file, you would be better served to just open it for reading and let the open failure inform you of the problem.
Upvotes: 2