Linux系统lseek函数作用

本文介绍了lseek函数的基本用法及其实现文件扩展和获取文件大小的功能。通过示例代码展示了如何使用lseek配合write来扩展文件大小,并演示了如何利用lseek获取文件的实际长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先看下函数:   off_t lseek(int fd, off_t offset, int whence);

 所需要头文件:

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

参数:

fd 表示要操作的文件描述符

offset是相对于whence(基准)的偏移量

whence 可以是SEEK_SET(文件指针开始),SEEK_CUR(文件指针当前位置) ,SEEK_END为文件指针尾

返回值:文件读写指针距文件开头的字节大小,出错,返回-1

lseek 主要作用是移动文件读写指针,因此还有以下两个作用

1.拓展文件,不过一定要一次写的操作。迅雷等下载工具在下载文件时候先扩展一个空间,然后再下载的。

2.获取文件大小

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


void main()
{
    int add_len = 1024*8;
    int fd=open("test.txt",O_RDWR);
    if(fd == -1)
    {
        perror("open test.txt");
        exit(-1);
    }
    lseek(fd,add_len-1,SEEK_END);
    write(fd,"0",1);

}

执行程序后


获取文件长度:

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


void main()
{
    int fd=open("test.txt",O_RDWR);
    if(fd == -1)
    {
        perror("open test.txt");
        exit(-1);
    }
    printf("file len:%d \n",lseek(fd,0,SEEK_END));
    close(fd);

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值