使用stat函数检查是否存在并且在C中可执行

时间:2016-02-28 22:35:33

标签: c

例如,我在当前工作目录下有目录a和b。我正在尝试找到文件X,如何修改stat()命令,以便检查目录a和b而不是当前工作目录? stat(a/file, &buf)会工作吗?另外,为了检查它是否可执行,我知道代码是buf.S_IXUSRif (buf.S_IXUSR)是否有效?

谢谢!

1 个答案:

答案 0 :(得分:1)

我建议您查阅stat(2)手册页。

以下是如何使用stat

的示例
struct stat buf;

if (stat("a/file", &buf) != 0) {
    // handle failure
}

// Check the `st_mode` field to see if the `S_IXUSR` bit is set
if (buf.st_mode & S_IXUSR) {
    // Executable by user
}

但是,对于您的用例,您可能会考虑使用access(2)

if (access("/path/to/file", X_OK) == 0) {
    // File exists and is executable by the calling process's
    // _real_ UID / GID.
}