Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c - 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:

I have a file (FILE1) and I want to create another file (FILE2) which has the same permissions of FILE1. Then I have to create another file (FILE3) which has the same permissions of FILE1 but only for the owner.

I would use chmod() to change permissions but I don't understand how to obtain the permissions of FILE1.

Can you please help me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The stat() and fstat() functions retrieve a struct stat, which includes a member st_mode indicating the file mode, where the permissions are stored.

You can pass this value to chmod() or fchmod() after masking out the non-file-permission bits:

struct stat st;

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...