曲径通幽论坛

标题: chmod [打印本页]

作者: beyes    时间: 2009-2-12 13:48
标题: chmod
改变文件或目录的权限:
#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





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2