转:基本IO函数的使用(lseek)

来源:互联网 发布:gif动态图制作软件 编辑:程序博客网 时间:2024/05/14 12:50

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;
}

原创粉丝点击