如何在 C 中更改/显示权限

问题描述 投票:0回答:3

我是 C 编程新手,我想在目录和子目录的文件上实现 chmod 命令。如何使用 C 代码更改/显示权限?有人可以帮忙举个例子吗?如果有人能给我提供代码,我将不胜感激。

c linux chmod
3个回答
14
投票

有一个 chmod 功能。来自 man 3p chmod

SYNOPSIS
   #include <sys/stat.h>

   int chmod(const char *path, mode_t mode);

...

如果你想读取权限,你可以使用 stat。来自 man 3p 统计

SYNOPSIS
   #include <sys/stat.h>

   int stat(const char *restrict path, struct stat *restrict buf);

...

如果您想像您提到的那样递归地执行此操作,则必须自己对

readdir
的结果进行循环。注意!:您必须从下往上设置权限,因为,例如,如果您将顶层目录设置为只读,则将不允许您在其下面设置任何内容。


2
投票

使用 GNU C 库,您应该能够直接使用

int chmod (const char *filename, mode_t mode)
int chown (const char *filename, uid_t owner, gid_t group)

查看这里..所有这些功能都在

sys/stat.h


1
投票

示例:(显示/测试权限)

struct stat st; 
int ret = stat(filename, &st);
if(ret != 0) {
    return false;
}   
if((st.st_mode & S_IWOTH) == S_IWOTH) {

} else {

}
© www.soinside.com 2019 - 2024. All rights reserved.