文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>lseek

lseek

时间:2009-04-23  来源:lxcrist

 作者:zieckey (zieckey@yahoo.com.cn)
    All Rights Reserved!

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。

示例程序:
运行结果:
[root@localhost src]# gcc lseek.c
[root@localhost src]# ./a.out
[root@localhost src]# cat temp.log
Hello woHello woHello woHello woHello woHello woHello woHello woHello woHello world!

/*******************************************************************************************
** Name:lseek.c
**        This program is used to show the usage of lseek() .
** Author:zieckey
** Date:2007/9/29
** All rights reserved!
*******************************************************************************************/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main(void)
{
    int fd, i, rev;
    char buf[] = "Hello world!";

    fd = open( "temp.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;
}

 

相关阅读 更多 +
排行榜 更多 +
飞翔之光手机版

飞翔之光手机版

冒险解谜 下载
飞翔之光手游

飞翔之光手游

冒险解谜 下载
月亮冲突英雄

月亮冲突英雄

飞行射击 下载