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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2539710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:59:21  来源:igfitidea点击:

How to change/show permissions in C

clinuxchmod

提问by speed17

I am new to C programming and I'd like to implement chmod command on files of a dir and subdir. How can I change/show permissions with a C code? Could someone help with a example? I would appreciate if anyone can provide me a code.

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

回答by Cascabel

There's a chmod function. From man 3p chmod:

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

SYNOPSIS
   #include <sys/stat.h>

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

...

If you want to read the permissions, you'd use stat. From man 3p stat:

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

SYNOPSIS
   #include <sys/stat.h>

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

...

If you want to do it recursively like you mentioned, you'll have to do the looping over results of readdiryourself.

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

回答by Hyman

with the GNU C library you should be able to do it directly with

使用 GNU C 库,您应该可以直接使用

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

check it out here.. all these functions are in sys/stat.h

这里查看..所有这些功能都在sys/stat.h

回答by songhir

a example:(show/test permissions)

一个例子:(显示/测试权限)

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

} else {

}