Using stat to check if a file is executable in C

Joseph Kahn picture Joseph Kahn · Oct 27, 2012 · Viewed 21.7k times · Source

For homework I have to write a C program and one of the things it has to do is check to see a file exists and if it is executable by the owner.

Using (stat(path[j], &sb) >= 0 I'm able to see if the file indicated by path[j] exists.

I've looked through man pages, a lot of questions and answers on stackoverflow, and several websites but I'm not able to wrap my head around exactly how to check if a file is executable using stat. I thought it would be as simple as ((stat(path[j], &sb) >= 0) && (sb.st_mode > 0) && (S_IEXEC) but as far as I can tell by testing it, it seems to ignore the fact that these files aren't executable.

I think that perhaps stat doesn't work the way I think it does. Assuming I use stat, how can I go about fixing this?

Answer

md5 picture md5 · Oct 27, 2012

You can indeed use stat to do this. You just have to use S_IXUSR (S_IEXEC is an old synonym of S_IXUSR) to check if you have execute permission. Bitwise AND operator (&) checks whether the bits of S_IXUSR are set or not.

if (stat(file, &sb) == 0 && sb.st_mode & S_IXUSR) 
    /* executable */
else  
    /* non-executable */

Example:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc > 1) {
        struct stat sb;
        printf("%s is%s executable.\n", argv[1], stat(argv[1], &sb) == 0 &&
                                                 sb.st_mode & S_IXUSR ? 
                                                 "" : " not");
    }
    return 0;
}