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

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

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

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

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

代码:

#include
#include
#include
#include
#include
#include
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文件操作)