Is it possible to use write() in file opened with

2019-08-01 15:02发布

#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?

标签: c file
1条回答
趁早两清
2楼-- · 2019-08-01 15:16

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.)

查看更多
登录 后发表回答