考虑下面的代码(它应该在的“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