Rella
Rella

Reputation: 66935

How to check if file is executable in C++?

So I have a path to file. How to check if it is executable? (unix, C++)

Upvotes: 3

Views: 8285

Answers (7)

einpoklum
einpoklum

Reputation: 131415

You might use this:

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

int is_executable_file(char const * file_path)
{
    struct stat sb;
    return 
        (stat(file_path, &sb) == 0) &&  
        S_ISREG(sb.st_mode) && 
        (access(file_path, X_OK) == 0);
}

Why not just access()? Since it will accept directories which can be recursed - which are not executable files.

If you want to be a little more standard-friendly and can use C++17, try:

#include <filesystem>
#include <unistd.h>

int is_executable_file(const std::filesystem::path& file_path)
{
    return 
        std::filesystem::is_regular_file(file_path) &&
        (access(file_path.c_str(), X_OK) == 0);
}

Upvotes: 0

jbruni
jbruni

Reputation: 1247

There is a caveat at the bottom of the man page for access(2):

CAVEAT Access() is a potential security hole and should never be used.

Keep in mind that a race condition exists between the time you call access() with a path string and the time you try to execute the file referred by the path string, the file system can change. If this race condition is a concern, first open the file with open() and use fstat() to check permissions.

Upvotes: 4

Robᵩ
Robᵩ

Reputation: 168596

Consider using access(2), which checks for permissions relative to the current process's uid and gid:

#include <unistd.h>
#include <stdio.h>

int can_exec(const char *file)
{
    return !access(file, X_OK);
}

int main(int ac, char **av) {
    while(av++,--ac) {
        printf("%s: %s executable\n", *av, can_exec(*av)?"IS":"IS NOT");
    }
}

Upvotes: 1

Paul Beckingham
Paul Beckingham

Reputation: 14895

access(2):

#include <unistd.h>

if (! access (path_name, X_OK))
    // executable

Calls to stat(2) have higher overhead filling out the struct. Unless of course you need that extra information.

Upvotes: 8

David R Tribble
David R Tribble

Reputation: 12204

Check the permissions (status) bits.

#include <sys/stat.h>

bool can_exec(const char *file)
{
    struct stat  st;

    if (stat(file, &st) < 0)
        return false;
    if ((st.st_mode & S_IEXEC) != 0)
        return true;
    return false;
}

Upvotes: 6

Jay
Jay

Reputation: 14441

You probably want to look at stat

Upvotes: 3

Cubbi
Cubbi

Reputation: 47408

You would have to call the POSIX function stat(2) and examine st_mode field of the stuct stat object it would fill in.

Upvotes: 3

Related Questions