How can I copy permissions from a file that already exists?

c, file-permissions, linux, unix

Solution

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

Problem

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?

Original source