开发者

fopen and open produce files with different file permissions

开发者 https://www.devze.com 2023-01-09 15:24 出处:网络
These two code snippets produce files with different file-permissions. Example 1 creates the expected default file-permissions but Example 2 does not. What\'s the explanation for this?

These two code snippets produce files with different file-permissions. Example 1 creates the expected default file-permissions but Example 2 does not. What's the explanation for this?

OS: Mac OS X version: 10.6.4

Xcode version: 3.2.2, 64 bit


// Example 1
FILE *fh1 = fopen("Test1.txt", "w+x");

if (fh1) {
    fwrite("TEST1", 1, 5, fh1);
    fclose(fh1);
}

Creates: -rw-r--r-- 1 me staff 5 29 Jul 00:41 Test开发者_开发知识库1.txt

// Example 2
int fh2 = open("Test2.txt", O_EXCL | O_CREAT | O_WRONLY);

if (fh2 >= 0) {
    write(fh2, "TEST2", 5);
    close(fh2);
}

Creates: ---------- 1 me staff 5 29 Jul 00:41 Test2.txt


When you use O_CREAT you need to add a third argument to open, the mode. For instance:

int fh2 = open("Test2.txt",
               O_EXCL | O_CREAT | O_WRONLY,
               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);

This would be equivalent to 0666. Be aware that this mode is then masked by the process's umask, meaning the permissions you specify will usually be reduced a bit. A typical umask is 0022, which would result in a mode of 0666 & ~0222 = 0644, i.e. -rw-r--r--.

From man open:

The oflag argument may indicate that the file is to be created if it does not exist (by specifying the O_CREAT flag). In this case, open requires a third argument mode_t mode; the file is created with mode mode as described in chmod(2) and modified by the process' umask value (see umask(2)).


int open(const char *pathname, int flags, mode_t mode);

The argument mode specifies the permissions to use in case a new file is created. See http://linux.about.com/od/commands/l/blcmdl2_open.htm

In your case, you'll want to set mode with value 0644

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号