2012-04-17 60 views
1

使用open系统调用来编写和创建文件,文件没有属性。 fedora16 GCC-4.6.3linux文件属性

#include <stdlib.h> 
#include <unistd.h> 
#include <fcntl.h> 

int main() 
{ 
    char * str= "helloworld"; 
    int fd = open("test.db",O_WRONLY|O_CREAT|O_TRUNC|O_APPEND); 

    write(fd,str,10); 

    close(fd); 
    return 0; 
} 

LL test.db的

----------。 17年4月14日11:34 test.db的

1个谟谟虽然它不创建默认文件的文件属性,例如像touch test.db

的umask:0002

如果跌落O_TRUNC int fd = open("test1.db",O_WRONLY|O_CREAT|O_APPEND) 文件attributs是:

---- rwx ---。 1个谟谟17年4月14日12:29 test1.db

+1

什么是你在你的shell的umask? – mjbnz 2012-04-17 04:24:16

+0

umask 0002(我已更新问题) – jiamo 2012-04-17 04:37:21

回答

3

添加所需权限的open()系统调用:

int fd = open("test.db",O_WRONLY|O_CREAT|O_TRUNC|O_APPEND, 0666); 

从文档:

mode must be specified when O_CREAT is in the flags, and is ignored otherwise. 
The argument mode specifies the permissions to use in case a new file is created. 
+0

值得描述:0666通常是正确的第三个参数值,因为通常会创建一个数据文件,其权限应该是“读写所有人,减去用户umask的”。对于某些应用程序,“正确的”第三个参数是0444或0600或0400,但那些不太常见。对于少数(例如编译的最后阶段),“正确的”第三个参数甚至是0777。 – torek 2012-04-17 04:51:18

1

您需要将模式传递给open。然后它也会设置权限。 open是一个变量参数功能,你可以通过更多的参数给它

int open(const char *path, int oflag, ...); 

这样做

open(LOCKFILE, O_WRONLY | O_CREAT | O_EXCL, 
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); 

检查各种权限位here