【问题标题】:How can I copy permissions from a file that already exists?如何从已经存在的文件中复制权限?
【发布时间】:2013-08-04 15:35:35
【问题描述】:

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

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

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

你能帮帮我吗?

【问题讨论】:

标签: c linux unix file-permissions


【解决方案1】:

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");
    }
}

【讨论】:

    【解决方案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
    

    【讨论】:

      【解决方案3】:

      这个答案在其他两个之后。所以我只给你一些代码。

      #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     
      
      }
      

      【讨论】:

      • 这是不正确的,传递给umask的值是在open()O_CREAT创建的文件中没有设置的权限。
      • @caf 我的错误。对不起。
      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 2015-12-09
      • 2017-07-18
      • 1970-01-01
      • 2011-07-17
      • 2018-11-17
      • 2014-04-11
      • 2014-11-02
      相关资源
      最近更新 更多