2

(Unix ライクなシステムで) C でプログラムを書かなければなりませんが、これが私の問題です:

ファイル (FILE1) があり、FILE1 と同じ権限を持つ別のファイル (FILE2) を作成したいと考えています。次に、FILE1 と同じパーミッションを持つ別のファイル (FILE3) を作成する必要がありますが、所有者のみが対象です。

chmod() を使用してパーミッションを変更しますが、FILE1 のパーミッションを取得する方法がわかりません。

手伝ってくれませんか?

4

3 に答える 3

8

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

この答えは、他の 2 つの後です。だから私はあなたにいくつかのコードを与えるだけです。

#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 に答える