如何从已存在的文件复制权限?

时间:2013-08-03 11:51:36

标签: c linux unix file-permissions

我必须用C编写程序(在类Unix系统上),这是我的问题:

我有一个文件(FILE1),我想创建另一个文件(FILE2),它具有与FILE1相同的权限。然后我必须创建另一个文件(FILE3),该文件具有与FILE1相同的权限,但仅限于所有者。

我会使用chmod()来更改权限,但我不明白如何获取FILE1的权限。

你能帮帮我吗?

3 个答案:

答案 0 :(得分:7)

stat()fstat()函数检索struct stat,其中包含一个成员st_mode,表示存储权限的文件模式。

在屏蔽掉非文件权限位后,您可以将此值传递给chmod()fchmod()

struct stat st;

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

答案 1 :(得分:2)

使用stat(2)系统调用。

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

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

将以下标记与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

答案 2 :(得分:1)

这个答案是在另外两个之后。所以我只给你一些代码。

#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     

}
相关问题