1. 程式人生 > >設定檔案的檔案訪問許可權為:rw-r--r--

設定檔案的檔案訪問許可權為: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");
}