曲径通幽论坛

标题: lseek [打印本页]

作者: beyes    时间: 2008-11-16 23:11
标题: lseek
NAME
       lseek - reposition read/write file offset(重定位文件读写指针)

包含头文件
       #include <sys/types.h>
       #include <unistd.h>

函数原型
        off_t lseek(int fd, off_t offset, int whence);

参数
        fd      文件描述符
        offset  移动的距离(偏移)
        base    SEEK_SET  =>   文件的开始
                SEEK_CUR  =>   当前的位置
                SEEK_END  =>   文件的结尾

返回值
        -1     遇到错误
       成功,从文件开始到定位处的字节数.

lseek 改变文件描述符所关联的指针的位置,新的位置由 offset 和 whence 来指定, whence 是基准位置,offset 是从基准位置开始的偏移量。基准位置可以是文件的开始(0)、当前位置(1)或文件的结尾(2)。注意,偏移量可以是负的。
作者: beyes    时间: 2009-2-7 22:38
lseek 系统调用设置文件描述符的 read/write 的指针。也就是说,你可以使用它设置文件的下一次读或下一次写将发生在什么哪里。你可以设置指针到一个文件中的绝对位置或者一个相对当前位置抑或文件末尾的相对位置。

如果定位失败,则返回 -1 ;如果成功则返回从文件开始到偏移地的偏移量,这个偏移量用字节来计算。

off_t 类型用来表达 offset 量,是一个依赖处理器类型(implementation-dependent)的整形量,被定义在 sys/types.h 中。
作者: beyes    时间: 2009-2-8 00:15
假设下面代码编译得到的程序和一个叫做 test.txt 的文件在同一个目录下,其中的内容是:
ok,the world is good
hell is terrible!
测试代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

main()
{
        int fd;
        off_t offset;

        fd = open("test.txt", O_RDONLY);

        offset = lseek(fd, -10, SEEK_END);

        printf("The offset is %d\\n",offset);

        offset = lseek(fd, 5, SEEK_CUR);
        printf("The offset is %d\\n",offset);

        return 0;
}

运行程序后
[root@localhost LSEEK]# ./lseek.exe
The offset is 29
The offset is 34





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2