是否有可能使用带O_APPEND模式打开写()的文件? [英] Is it possible to use write() in file opened with O_APPEND mode?
问题描述
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
FILE * fp;
char buf[128];
int fd = open("/home/pdave/Downloads/ccode/fileout1",O_CREAT);
printf("fd after creat:%d",fd);
close(fd);
fd = open("/home/pdave/Downloads/ccode/fileout1",O_APPEND);
printf("fd after append:%d",fd);
int more=1;
int ret=0;
while(more){
puts("enter text:");
scanf("%s",buf);
puts(buf);
ret=write(fd,buf,128);
printf("ret:%d",ret);
puts("more?");
scanf("%d",&more);
}
}
以上尝试写字符在 O_APPEND
模式open函数打开的文件。它的工作原理,当它打开与 O_WRONLY
模式,而不是在它的 O_APPEND
打开。我怎样才能追加到它不与W打开,然后用求 SEEK_END
然后的fputs
来的文件或者类似的东西?
The above tries to write characters to a file opened with the open function in O_APPEND
mode. It works when it is opened with O_WRONLY
mode but not when it is opened in O_APPEND
. How can I append to it without opening with "w" and then using seek to SEEK_END
and then fputs
to the file or something like that?
推荐答案
使用 O_WRONLY | O_APPEND
,你仍然需要的文件访问模式。 (对于某些[最?]编译器,不包括文件访问标志将导致文件被视为只读的,如果没有的话你有一个 EINVAL
错误。)
Use O_WRONLY | O_APPEND
, you still need the file access mode. (For some [most?] compilers, not including a file access flag will cause the file to be treated as read-only, and if not then you'd have an EINVAL
error.)
这篇关于是否有可能使用带O_APPEND模式打开写()的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!