【问题标题】:Removing permissions on a file? C Programming删除文件的权限? C 编程
【发布时间】:2015-05-18 02:24:04
【问题描述】:

使用 chmod 我可以分配权限,例如

chmod(file, S_IRUSR);

有没有办法只剥夺用户的读取权限?

我试过了

chmod(file, !S_IRUSR);

和 chmod(文件, -S_IRUSR);

都不行。

【问题讨论】:

    标签: c linux unix permissions chmod


    【解决方案1】:

    您不能像使用命令行实用程序那样使用chmod(2) 更改单个权限位。您只能设置新的完整权限集。

    要实现更改,您需要先读取它们,使用stat(2),从st_mode 字段切换所需的位,然后使用chmod(2) 设置它们。

    以下代码将清除test.txtS_IRUSR 位,并设置S_IXUSR 位。 (为简洁起见,省略了错误检查。)

    #include <sys/stat.h>
    
    int main(void)
    {
        struct stat st;
        mode_t mode;
        const char *path = "test.txt";
    
        stat(path, &st);
    
        mode = st.st_mode & 07777;
    
        // modify mode
        mode &= ~(S_IRUSR);    /* Clear this bit */
        mode |= S_IXUSR;       /* Set this bit   */
    
        chmod(path, mode);
    
        return 0;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2018-08-16
    • 2019-08-19
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多