原文链接:http://c.biancheng.net/cpp/html/236.html
相关函数:dup, open, fseek
头文件:#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 允许负值的出现.
下列是较特别的使用方式:
- 欲将读写位置移到文件开头时:lseek(int fildes, 0, SEEK_SET);
- 欲将读写位置移到文件尾时:lseek(int fildes, 0, SEEK_END);
- 想要取得目前文件位置时:lseek(int fildes, 0, SEEK_CUR);
返回值:当调用成功时则返回目前的读写位置, 也就是距离文件开头多少个字节. 若有错误则返回-1, errno 会存放错误代码.
附加说明:Linux 系统不允许lseek()对tty 装置作用, 此项动作会令lseek()返回ESPIPE.
以下程序创建一个有空洞的文件:
/* Standard C header */
#include <stdio.h>
/* Unix header */
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
char buf1[] = "abcdefghij";
char buf2[] = "ABCDEFGHIJ";
int main(void)
{
int fd, size;
if ((fd = creat("file.hole", S_IRUSR|S_IWUSR)) < 0)
{
printf("creat error\n");
return -1;
}
size = sizeof buf1 - 1;
if (write(fd, buf1, size) != size)
{
printf("buf1 write error\n");
return -1;
}
/* offset now = 10 */
if (lseek(fd, 16384, SEEK_SET) == -1)
{
printf("lseek error\n");
return -1;
}
/* offset now = 16384 */
size = sizeof buf2 - 1;
if (write(fd, buf2, size) != size)
{
printf("buf2 write error\n");
return -1;
}
/* offset now = 16394 */
return 0;
}