问题描述
在stat.h中,有一些常量/定义,例如:
#define S_IRWXU 0000700 /* RWX mask for owner */
#define S_IRUSR 0000400 /* R for owner */
#define S_IWUSR 0000200 /* W for owner */
#define S_IXUSR 0000100 /* X for owner */
我知道我可以使用stat
来获取“一切”:
$ stat file.txt
File: file.txt
Size: 5307 Blocks: 16 IO Block: 4096 regular file
Device: 10302h/66306d Inode: 13129530 Links: 1
Access: (0775/-rwxrwxr-x) Uid: ( 1000/ ubuntu) Gid: ( 1000/ ubuntu)
Access: 2020-09-25 21:47:31.013446496 +0000
Modify: 2020-09-25 22:34:21.527460575 +0000
Change: 2020-09-25 22:34:21.531460600 +0000
Birth: -
在C中,我如何访问文件的结构以检查文件是否具有其他可执行权限,等效于:
// if the file in question has executable permissions for 'other'
if (file.txt & S_IXOTH) {
// do something
}
解决方法
stat
是Linux系统调用,而不仅仅是shell命令。
这意味着您可以编写如下代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat buf;
if (0 == stat("file.txt",&buf)) {
if (buf.st_mode & S_IXOTH) {
/* do what you wanted */
}
} else {
/* handle error accessing the file here **/
}
return 0;
}