`

设置了O_APPEND,lseek的操作将无效

 
阅读更多

下面 的代码说明,设置了O_APPEND,语句“lseek(fd, 0, SEEK_SET)”并没有起到应有的作用

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
int main(int argc, char** argv){
        int fd;
        char* fName = "text.txt";
        if((fd = open(fName, O_CREAT | O_APPEND | O_RDWR)) < 0){
                fprintf(stderr, "open file %s error !\n msg:%s\n", fName, strerror(errno));
                exit(1);
        }
        int num = 10, i;
        for(i = 0; i < num; i++){
                if(lseek(fd, 0, SEEK_SET) < 0){
                        fprintf(stderr, "seek file %s error !\n msg:%s\n", fName, strerror(errno));
                        exit(1);
                }
                char* content = "1";
                if(write(fd, content, 1) < 0){
                        fprintf(stderr, "write file %s error !\nmsg:%s\n", fName, strerror(errno));
                        exit(1);
                }
        }
        exit(0);
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics