如何检查文件在C++中是否可执行?

Rel*_*lla 2 c++ unix api

所以我有一个文件路径.如何检查它是否可执行?(unix,C++)

Dav*_*ble 7

检查权限(状态)位.

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 但这回答"可以*有人*执行文件吗?" 不是"可以*我*执行文件吗?" 也许OP应该考虑[access(2)](http://linux.die.net/man/2/access). (2认同)

Pau*_*ham 7

访问(2):

#include <unistd.h>

if (! access (path_name, X_OK))
    // executable
Run Code Online (Sandbox Code Playgroud)

调用stat(2)会有更高的开销填写结构.除非您需要额外的信息.

  • 您是说access()本身不是通过执行stat()和getpid(),getuid(),getgid()来实现的吗?我会认为开销几乎相同。 (2认同)