2012-04-17 87 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