lseek
名称:重新定位文件的读/写位置
总揽:
#include
#include
off_t lseek(int fd,off_t offset,int whence)
#include
off_t lseek(int fd,off_t offset,int whence)
描述:
lseek()函数用来重新定位打开的文件(文件描述符fd)的读写位置为距离whence的偏移量
为offset.
whence可能的值:
SEEK_SET:偏移量为据文件开头offset字节
SEET_CUR:偏移量为据当前位置offset字节
SEEK_END:偏移量为据文件末尾offset字节
offset:代表偏移量的整数可以为负数.
返回值:
一旦执行成功,lseek()返回文件的偏移量,否则返回-1,并设置errno.
实例:
#include
#include
#include
#include
int main(void)
{
int fd;
off_t off;
fd=open("test.txt",O_RDWR);
if(fd==-1){
perror("Fail to open");
exit(1);
}
printf("Locating\n");
off=lseek(fd,5,SEEK_CUR);
if(off==-1){
perror("Fail to lseek");
exit(1);
}
#include
#include
#include
int main(void)
{
int fd;
off_t off;
fd=open("test.txt",O_RDWR);
if(fd==-1){
perror("Fail to open");
exit(1);
}
printf("Locating\n");
off=lseek(fd,5,SEEK_CUR);
if(off==-1){
perror("Fail to lseek");
exit(1);
}
printf("Writing\n");
if(write(fd,"Hello\n",6)==-1){
perror("Fail to write");
exit(1);
}
if(write(fd,"Hello\n",6)==-1){
perror("Fail to write");
exit(1);
}
close(fd);
return 0;
}
return 0;
}