lseek函数的使用

需要包含头文件:<sys/types.h>  <unistd.h>

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

函数功能:移动文件读写指针;获取文件长度;拓展文件空间。

在使用该函数之前需要将文件打开!  off_t 有符号整型   fd为文件描述符  offset参数指定偏移量   whence参数指定具体从哪个位置开始偏移: SEEK_SET 文件头   SEEK_CUR 当前指针位置   SEEK_END 文件尾(注意文件尾为文件结束符EOF=-1) 

返回值:较文件起始位置向后的偏移量(到文件读写指针的位置)  其可以大于当文件读写指针处于文件末尾时的偏移量,此时文件空间被拓展。

获取文件长度: lseek( fd , 0 , SEEK_END);  返回值即为文件长度。

 

//获取一个文件的长度并且拓展该文件的空间

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main( )
{
    int fd;
    fd = open("file",O_WRONLY);   //打开file文件
    if( fd == -1 )
    {
        perror(" open file " );
        exit(1);
    }

    int length;
    length = lseek( fd , 0 , SEEK_END );  //获取file文件的长度
    printf(" The length of the file is %d.\n",length);
  
    length=lseek( fd , 3000 , SEEK_END );  //拓展file文件空间,增加3000字节
    printf(" The length of the file is %d.\n",length);  //注意此时文件实质上还没有被拓展,需要在末位写入一些数据
    int fd1;
    fd1 = write( fd , "a" , 1);   //此时文件才被拓展,在文件末位写入一个字节的数据
    if( fd1 == -1 )
    {
        perror(" write file " );
        exit(1);
    }
    length = lseek( fd , 0 , SEEK_END );
    printf(" The length of the file is %d, after lengthen.\n",length);

    int qw;
    qw = close(fd);
    if( qw == -1 )
    {
        perror( "close file");
        exit(1);
    }

    return 0;
}

[root@localhost work]# vim file

[root@localhost work]# ./rdwr

 The length of the file is 64.

 The length of the file is 3064.

 The length of the file is 3065, after lengthen.

 [root@localhost work]# vim rdwr.c

[root@localhost work]# ll file

-rwxrwxrwx. 1 root root 3065 Mar 19 16:54 file   //最终文件大小为3065Bytes

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值