lseek()函数的使用说明

来源:互联网 发布:股票抢涨停软件 编辑:程序博客网 时间:2024/05/19 04:03

 lseek(移动文件的读写位置)      
     #include<sys/types.h>
     #include<unistd.h>
定义函数: off_t lseek(int fildes,off_t offset ,int whence);
函数说明:
    每一个已打开的文件都有一个读写位置,当打开文件时通常其读写
    位置是指向文件开头,若是以附加的方式打开文件(如    O_APPEND)
    ,则读写位置会指向文件尾。当 read() 或 write()
    时,读写位置会随之增加,lseek()便是用来控制该文件的读写位
    置。参数 fildes 为已打开的文件描述词,参数 offset 为根据参数
    whence 来移动读写位置的位移数。参数 whence 为下列其中一种:
    SEEK_SET 参数 offset 即为新的读写位置。
    SEEK_CUR 以目前的读写位置往后增加 offset 个位移量。
    SEEK_END 将读写位置指向文件尾后再增加 offset 个位移量。
    当 whence 值为 SEEK_CUR 或 SEEK_END 时,参数 offet 允许负值
    的出现。
    下列是教特别的使用方式:
    1) 欲将读写位置移到文件开头时:lseek(int fildes,0,SEEK_SET)     ;
    2) 欲将读写位置移到文件尾时:lseek(int fildes,0,SEEK_END)      ;
    3) 想要取得目前文件位置时:lseek(int fildes,0,SEEK_CUR)      ;
   
 返回值     
     当调用成功时则返回目前的读写位置,也就是距离文件开头多少个
     字节。若有错误则返回-1,errno 会存放错误代码。

附加说明
    Linux 系统不允许 lseek()对 tty 装置作用,此项动作会令 lseek()
     返回 ESPIPE。

示例程序

/********************************************************
*****功能:测试lseek()函数
*****环境:linux
*****作者:彭伟中
***时间:20110809
********************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc,char **argv)
{
 int fd,i;
 char buf[]="Hello world!";
 fd=open("file.log",O_WRONLY|O_CREAT);
 for(i=0;i<10;i++)
 {
  write(fd,buf,sizeof(buf));
  lseek(fd,-5,SEEK_CUR);
 }
 close(fd);
 return 0;
}

[root@amu lseek]# vim lseek_c.c
[root@amu lseek]# gcc -o lseek_c lseek_c.c
[root@amu lseek]# ./lseek_c
[root@amu lseek]# cat file.log
Hello woHello woHello woHello woHello woHello woHello woHello woHello woHello worl

[root@amu lseek]#