设置文件的文件访问权限为:rw-r--r--

描述:rw- (user权限) / r– (group权限) / r– (others权限)

r: 读权限    w: 写权限     x: 执行权限

要求:输入文件名,打印输出该文件初始权限,以及修改为rw-r--r--后的权限

知识点:设置文件的多个权限位,对这些权限位进行按位或操作即可。S_IRUSR | S_IWUSR 

代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
    struct stat buf;
        int res;
        if(argc!=2)
        {
             perror("参数不正确!正确格式:./main filename");
                exit(1);
        }
        res=stat(argv[1],&buf);
        if(res<0)
        {
                perror("stat error");
                exit(1);
        }
            printf("初始文件 %s 的权限信息:\n",argv[1]);
            //if(buf.st_mode&S_IRWXU) printf("user read write execute\n");
            if(buf.st_mode&S_IRUSR) printf("user read \n");
            if(buf.st_mode&S_IWUSR) printf("user write \n");
            if(buf.st_mode&S_IXUSR) printf("user execute\n");
            //if(buf.st_mode&S_IRWXG) printf("group read write execute\n");
            if(buf.st_mode&S_IRGRP) printf("group read \n");
            if(buf.st_mode&S_IWGRP) printf("group write\n");
            if(buf.st_mode&S_IXGRP) printf("group execute\n");
            //if(buf.st_mode&S_IRWXO) printf("other read write execute\n");
            if(buf.st_mode&S_IROTH) printf("other read \n");
            if(buf.st_mode&S_IWOTH) printf("other write\n");
            if(buf.st_mode&S_IXOTH) printf("other execute\n");
            chmod(argv[1],S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
            res=stat(argv[1],&buf);
            if(res<0)
            {
                perror("stat error");
                exit(1);
            }
            printf("更改后文件 %s 的权限信息:\n",argv[1]);
            if(buf.st_mode&S_IRUSR) printf("user read \n");
            if(buf.st_mode&S_IWUSR) printf("user write \n");
            if(buf.st_mode&S_IXUSR) printf("user execute\n");
            if(buf.st_mode&S_IRGRP) printf("group read \n");
            if(buf.st_mode&S_IWGRP) printf("group write\n");
            if(buf.st_mode&S_IXGRP) printf("group execute\n");
            if(buf.st_mode&S_IROTH) printf("other read \n");
            if(buf.st_mode&S_IWOTH) printf("other write\n");
            if(buf.st_mode&S_IXOTH) printf("other execute\n");
}

阅读更多
文章标签: linux
个人分类: linux文件操作
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭