lseek

所有打开的文件都有一个当前文件偏移量(current file offset),以下简称为 cfo。cfo 通常是一个非负整数,用于表明文件开始处到文件当前位置的字节数。读写操作通常开始于 cfo,并且使 cfo 增大,增量为读写的字节数。文件被打开时,cfo 会被初始化为 0,除非使用了 O_APPEND 。

    使用 lseek 函数可以改变文件的 cfo 。

        #include

        off_t lseek(int filedes, off_t offset, int whence);

                    返回值:新的偏移量(成功),-1(失败)

参数 offset 的含义取决于参数 whence:

    1. 如果 whence 是 SEEK_SET,文件偏移量将被设置为 offset。 
    2. 如果 whence 是 SEEK_CUR,文件偏移量将被设置为 cfo 加上 offset, 
       offset 可以为正也可以为负。 
    3. 如果 whence 是 SEEK_END,文件偏移量将被设置为文件长度加上 offset, 
       offset 可以为正也可以为负。

SEEK_SET、SEEK_CUR 和 SEEK_END 是 System V 引入的,在这之前使用的是 0、1 和 2。

 

栗子;

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
main()
{
    int fd;
    float score;
    int r;
    int i=0;
    fd=open("stu.dat",O_RDWR);
    if(fd==-1) printf("open error:%m\n"),exit(-1);
        
    //定位
    /*
    for(i=0;i<2;i++)
    {
        r=lseek(fd,i*28,SEEK_SET);    
        r=lseek(fd,24,SEEK_CUR); 
        //r=lseek(fd,i*28+24,SEEK_SET);
        //读取
        r=read(fd,&score,sizeof(float));
        //打印 输出
        printf("%.2f\n",score);
    }*/
    /*
    r=lseek(fd,-100,SEEK_SET);
    printf("%d\n",r);
    //write(fd,"Hello",5);
    */
    for(i=0;i<2;i++)
    {
        pread(fd,&score,sizeof(float),i*28+24);
        printf("%.2f\n",score);
        read(fd,&score,sizeof(float));
        printf("%.2f\n",score);
    }
    
    close(fd);
}

 

posted @ 2017-02-28 15:03  ren_zhg1992  阅读(156)  评论(0)    收藏  举报