比如文件1.txt
#cat 1.txt
abcd
- #o_append.c
- #include
#include
int main(int ac, char * av[])
{
int fd;
char buf[] = "1234567";
off_t currpos;
int s;
if((fd=open(av[1], O_RDWR))==-1)
perror("open error");
s = fcntl(fd, F_GETFL);
s |= O_APPEND;
if(fcntl(fd, F_SETFL, s) == -1)
perror("set flag error");
if(lseek(fd, 0, SEEK_SET) == -1) //虽然这里把文件定位到开始处
perror("lseek error");
if(write(fd, buf, strlen(buf)) != strlen(buf)) //但是写后发现仍然被写到文件末尾
perror("write error");
currpos = lseek(fd, 0, SEEK_CUR); //获得当前seek的位置,可以看到已经是文件末尾
printf("currpos = %d\n", currpos);
if(lseek(fd, 0, SEEK_SET) == -1) //再次seek到开始处
perror("lseek error");
if(read(fd, buf, strlen(buf)) != strlen(buf)) //从开始处读入数据
perror("read error");
printf("read buf = %s\n", buf);
close(fd);
exit(0);
}