2

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

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

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

你能帮我么?

4

3 回答 3

8

和函数检索 a stat(),其中包括一个指示文件模式的成员,其中存储了权限。fstat()struct statst_mode

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

struct stat st;

if (stat(file1, &st))
{
    perror("stat");
} 
else
{
    if (chmod(file2, st.st_mode & 07777))
    {
        perror("chmod");
    }
}
于 2013-08-03T11:56:45.140 回答
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
于 2013-08-03T11:56:58.420 回答
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     

}
于 2013-08-03T12:28:15.593 回答