[英]How can I copy permissions from a file that already exists?
I have to write a program in C (on a Unix-like system) and this is my problem: 我必须用C编写一个程序(在类Unix系统上),这是我的问题:
I have a file (FILE1) and I want to create another file (FILE2) which has the same permissions of FILE1. 我有一个文件(FILE1),我想创建另一个文件(FILE2),它具有相同的FILE1权限。 Then I have to create another file (FILE3) which has the same permissions of FILE1 but only for the owner.
然后我必须创建另一个文件(FILE3),它具有相同的FILE1权限,但仅限于所有者。
I would use chmod() to change permissions but I don't understand how to obtain the permissions of FILE1. 我会使用chmod()来更改权限,但我不明白如何获取FILE1的权限。
Can you please help me? 你能帮我么?
The stat()
and fstat()
functions retrieve a struct stat
, which includes a member st_mode
indicating the file mode, where the permissions are stored. stat()
和fstat()
函数检索struct stat
,其中包含一个成员st_mode
指示存储权限的文件模式。
You can pass this value to chmod()
or fchmod()
after masking out the non-file-permission bits: 在屏蔽掉非文件权限位之后,您可以将此值传递给
chmod()
或fchmod()
:
struct stat st;
if (stat(file1, &st))
{
perror("stat");
}
else
{
if (chmod(file2, st.st_mode & 07777))
{
perror("chmod");
}
}
Use stat(2)
system call. 使用
stat(2)
系统调用。
int stat(const char *path, struct stat *buf);
struct stat {
....
mode_t st_mode; /* protection */
....
};
Use following flags with st_mode
. 将以下标志与
st_mode
一起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
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.