How can I copy permissions from a file that already exists?

人走茶凉 提交于 2019-11-27 08:20:37

问题


I have to write a program in C (on a Unix-like system) and this is my problem:

I have a file (FILE1) and I want to create another file (FILE2) which has the same permissions of FILE1. Then I have to create another file (FILE3) which has the same permissions of FILE1 but only for the owner.

I would use chmod() to change permissions but I don't understand how to obtain the permissions of FILE1.

Can you please help me?


回答1:


The stat() and fstat() functions retrieve a struct stat, which includes a member st_mode indicating the file mode, where the permissions are stored.

You can pass this value to chmod() or fchmod() after masking out the non-file-permission bits:

struct stat st;

if (stat(file1, &st))
{
    perror("stat");
} 
else
{
    if (chmod(file2, st.st_mode & 07777))
    {
        perror("chmod");
    }
}



回答2:


Use stat(2) system call.

int stat(const char *path, struct stat *buf);

struct stat {
    ....
    mode_t    st_mode;    /* protection */
    ....
};

Use following flags with st_mode.

S_IRWXU    00700     mask for file owner permissions
S_IRUSR    00400     owner has read permission
S_IWUSR    00200     owner has write permission
S_IXUSR    00100     owner has execute permission

S_IRWXG    00070     mask for group permissions
S_IRGRP    00040     group has read permission
S_IWGRP    00020     group has write permission
S_IXGRP    00010     group has execute permission

S_IRWXO    00007     mask for permissions for others (not in group)
S_IROTH    00004     others have read permission
S_IWOTH    00002     others have write permission
S_IXOTH    00001     others have execute permission



回答3:


This answer is after the other two. So I only give you some code.

#include <sys/stat.h>
#include <stdio.h>
int main()
{
     struct stat buffer;
     mode_t file1_mode;
     if(stat("YourFile1_PathName",&buffer) != 0)//we get all information about file1
     {printf("stat error!\n"); return -1;}
     file1_mode = buffer.st_mode;//now we get the permissions of file1
     umask(file1_mode^0x0777);//we set the permissions of file1 to this program.then all file create by this program have the same permissions as file1
     // ....do what you want  below     

}


来源:https://stackoverflow.com/questions/18032574/how-can-i-copy-permissions-from-a-file-that-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!