#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);
}
}
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?
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 anEINVAL
error.)