考慮下面的代碼(它應該在的「HelloWorld」文件寫的「HelloWorld」,然後閱讀文本):空調系統調用open /讀/寫/關閉和O_CREAT | O_EXCL
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FNAME "helloworld"
int main(){
int filedes, nbytes;
char buf[128];
/* Creates a file */
if((filedes=open(FNAME, O_CREAT | O_EXCL | O_WRONLY | O_APPEND,
S_IRUSR | S_IWUSR)) == -1){
write(2, "Error1\n", 7);
}
/* Writes hello world to file */
if(write(filedes, FNAME, 10) != 10)
write(2, "Error2\n", 7);
/* Close file */
close(filedes);
if((filedes = open(FNAME, O_RDONLY))==-1)
write(2, "Error3\n", 7);
/* Prints file contents on screen */
if((nbytes=read(filedes, buf, 128)) == -1)
write(2, "Error4\n", 7);
if(write(1, buf, nbytes) != nbytes)
write(2, "Error5\n", 7);
/* Close file after read */
close(filedes);
return (0);
}
我第一次運行該程序時,輸出爲:
helloworld
之後,我每次運行程序時,輸出爲:
Error1
Error2
helloworld
我不明白爲什麼文本沒有添加,因爲我已經指定了O_APPEND文件。 是因爲我包含了O_CREAT嗎? 它的文件已經創建好了,是不是應該忽略O_CREAT?
謝謝,通過刪除O_EXCL代碼是功能。你能解釋我使用O_EXCL嗎? – 2010-04-03 20:03:41