int main(void){
int fd;
char *str = "This is what I am writing in this txt.";
char buf[100];
size_t len = 30;
off_t currpos;
if((fd = open("./read.txt",O_RDWR | O_CREAT)) == -1){
fprintf(stderr,"open() failed: %s\n",strerror(errno));
}
printf("fd = %d\n",fd);
if(write(fd,str,len) == -1){
fprintf(stderr,"write() failed: %s\n",strerror(errno));
}
if((currpos = lseek(fd,0,SEEK_CUR)) == -1){
fprintf(stderr,"lseek() failed: %s\n",strerror(errno));
}
printf("currpos = %d\n",currpos);
if((currpos = lseek(fd,0,SEEK_SET)) == -1){
fprintf(stderr,"lseek() failed: %s\n",strerror(errno));
}
printf("currpos = %d\n",currpos);
if(read(fd,buf,len) == -1){
fprintf(stderr,"read() failed: %s\n",strerror(errno));
}
printf("str = %s\n",str);
printf("buf = %s\n",buf);
close(fd);
exit(0);
}
问题解释: write完成后, 将此时offset偏移量输出时会发现offset=30, 而下次写或者读时会在偏移后的位置继续, 所以必须让offset回到文件开始的位置, 即offset为0时才能完整读出刚刚写入的数据
总结: 文件的偏移量offset是不会体现在read, write等函数中的, 下面是APUE中的原话lseek仅将该偏移量记录在内核, 并不引起任何IO操作, 用于下一个读或写操作