(5)关于Linux系统的lseek函数误区指南(附测试源码)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int fd1,fd2;
int ret;
char buf[128]={0};
fd1 = open("./test_file",O_TRUNC|O_RDWR);
if(-1 == fd1){
perror("open error");
return -1;
}
lseek(fd1,0,SEEK_END);
ret = write(fd1,"HELLO WORLD",11);
if (-1 == ret)
{
perror("write error");
close(fd1);
return -1;
}
fd2 = open("./test_file",O_RDWR);
lseek(fd2,0,SEEK_END);
ret = write(fd2,"My Love",7);
if(-1 == ret)
{
perror("read error");
close(fd1);
return -1;
}
lseek(fd2,0,SEEK_SET);
ret = read(fd2,buf,18);
if(-1 == ret){
perror("read error");
close(fd1);
close(fd2);
return -1;
}
printf("read is %s\n",buf);
close(fd1);
close(fd2);
}
/*验证结论 : 对于lseek函数。将文件做末尾对齐时 它会从已经写的字节的开头开始写
即 如果你已经写了一些内容如下
buf=[HELLO WORLD]
此时再进行末尾写入
得到的结果为
buf=[HELLO WORLDMy Love]
*/