2015-02-11 29 views
1

文件這是我第一次使用open()來自:使用open()來創建用C

#include <fcntl.h> 

我想創建兩個文件:

int fd; 
int fd2; 
char *tmpname = "./TMPFILE"; 
printf("Temporary file created\n "); 
char *tmpname2 = "./TMPFILE2"; 
printf("Temporary file two created\n "); 
fd = open(tmpname, O_WRONLY | O_APPEND); 
fd2 = open(tmpname2, O_WRONLY | O_APPEND); 

我想在當前工作目錄中創建可寫入和附加到的文件。

這編譯和運行,但我擔心的是,當我檢查我的目錄,看看是否創建文件,他們沒有列出。

我的問題是open()只會在程序運行後刪除臨時文件,或者是我搞砸了嗎?

+0

ü沒有做「LS -ail」 - 即強制開始文件中包含的「」 – pm100 2015-02-11 23:41:26

+0

@ pm100是的,我試過,沒有。 – TheDude1142 2015-02-11 23:44:07

回答

3

創建文件時,需要打開第三個參數(mode)。如果你不這樣做,就會發生不可預知的事情。

另外,如果你想創建一個文件,如果它不存在,則需要O_CREAT或運算中,即

fd = open(tmpname, O_WRONLY | O_APPEND | O_CREAT, 0644); 

O_CREAT(粗略地講)創建文件,如果它不存在。

從手冊頁:

 
NAME 
     open, creat - open and possibly create a file or device 

SYNOPSIS 
     #include 
     #include 
     #include 

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

     int creat(const char *pathname, mode_t mode); 

... 
     O_CREAT 
       If the file does not exist it will be created. The owner (user ID) of 
       the file is set to the effective user ID of the process. The group 
       ownership (group ID) is set either to the effective group ID of the 
       process or to the group ID of the parent directory (depending on 
       filesystem type and mount options, and the mode of the parent direc‐ 
       tory, see the mount options bsdgroups and sysvgroups described in 
       mount(8)). 

       mode specifies the permissions to use in case a new file is created. 
       This argument must be supplied when O_CREAT is specified in flags; if 
       O_CREAT is not specified, then mode is ignored. The effective permis‐ 
       sions are modified by the process's umask in the usual way: The per‐ 
       missions of the created file are (mode & ~umask). Note that this mode 
       applies only to future accesses of the newly created file; the open() 
       call that creates a read-only file may well return a read/write file 
       descriptor. 

+2

如果一切都失敗RTFM :-) – pm100 2015-02-11 23:45:10

+0

@abligh那麼,你知道,我是一個白癡哈哈。感謝您的幫助。下次我只會聽取建議並閱讀手冊。 – TheDude1142 2015-02-11 23:47:59