lseek()函数的用法

2009年11月24日 10:41    发布者:李宽
在BT代码的缓冲管理中经常会看到这函数,功能是移动文件的读写指针,可以先在Linux的Sheel下看一下他的函数原型:

NAME
lseek - reposition read/write file offset

SYNOPSIS
#include <sys/types.h>
#include <unistd.h>

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

DESCRIPTION
The lseek() function repositions the offset of the open file associated
with the file descriptor fd to the argument  offset  according  to  the
directive whence as follows:

SEEK_SET
The offset is set to offset bytes.

SEEK_CUR
The offset is set to its current location plus offset bytes.

SEEK_END

参数说明:
fd为已打开的文件描述符;
off_t_offset为偏移量,它是根据下面的whence的取值;
whence有3种取值:
SEEK_SET 将读写位置指向文件头后增加offset个位移量;
SEEK_CUR 以目前的读写位置往后增加offset个位移量;
SEEK_END 将读写位置指向文件尾后增加offset个位移量;
但是有时候,在旧的代码中可能看到不是SEEK_XXX这样的参数,这是由于新旧值的原因,下面是他们的对应关系:
旧值                 新值
0                    SEEK_SET
1                    SEEK_CUR
2                    SEEK_END
L_SET             SEEK_SET
L_INCR            SEEK_CUR
L_XTND          SEEK_END

作者:阿吴网志 2009-11-23