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

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

我有一个文件(FILE1),我想要创build另一个文件(FILE2)具有FILE1相同的权限。 然后,我必须创build另一个文件(FILE3)具有FILE1相同的权限,但只为所有者。

我将使用chmod()更改权限,但我不知道如何获得FILE1的权限。

你能帮我么?

Solutions Collecting From Web of "如何从已存在的文件复制权限?"

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

使用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 

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

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