曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3550|回复: 0
打印 上一主题 下一主题

chmod

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2009-2-12 13:48:18 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
改变文件或目录的权限:
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);

 path 参数来指定要改变的文件;mode 参数说明修改的权限内容,形式和 open 系统调用里的一样,可以用 OR 运算服进行权限的或操作。除非程序已经给了适当的特权,不然只有文件的拥有者或者超级用户具有修改权限的能力。

示例程序
假设目录下有一文件的权限为:
 ll test.txt
---------- 1 groad users 19 05-30 12:16 test.txt
现在用 chmod 函数来修改这个文件的权限,代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{

    if (chmod ("test.txt", S_IRUSR | S_IWUSR | S_IWGRP | S_IWGRP | S_IWOTH) < 0) {
        perror ("chmod");
        exit (EXIT_FAILURE);
    }

    return (0);
}
运行程序后,查看test.txt的文件权限:
 ll test.txt
---------- 1 groad users 19 05-30 12:16 test.txt

想要取消相关权限位,再给文件添加上权限修饰位:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char **argv)
{
    struct stat buf;


    if (chmod ("test.txt", S_IRUSR | S_IWUSR | S_IWGRP | S_IWGRP | S_IWOTH) < 0) {
        perror ("chmod");
        exit (EXIT_FAILURE);
    }
   
    if (stat ("test.txt", &buf) < 0) {
        perror ("stat");
        exit (EXIT_FAILURE);
    }
    chmod ("test.txt", (buf.st_mode & ~S_IWGRP | S_ISGID));

    return (0);
}
运行程序后查看文件权限:
ll test.txt
-rw---S-w- 1 groad users 19 05-30 12:16 test.txt
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-7 05:07 , Processed in 0.371820 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表