Linux lseek函数

接口:off_t lseek(int fd, off_t offset, int whence);

头文件:
#include<sys/types.h>
#include<unistd.h>

一、参数
1.fd:要操作的文件对应的文件描述符
2.offset:相对于whence的偏移量
3.whence:可以为SEEK_SET(0),SEEK_CUR(1),SEEK_END(2);
SEEK_SET:将读写位置移动到文件头后再增加offset个字节
SEEK_CUR:将读写位置移动到当前指定位置后再增加offset个字节
SEEK_END:将读写位置移动到文件结尾后再增加offset个字节

二、返回值:成功则返回当前读写位置,即目前的文件指针距文件开头有多少个字节;失败则返回-1

三、功能:
1.设置文件指针的位置
2.拓展文件大小

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

int main(int argc, char* argv[])
{
    //创建文件
    int fd = open("test.txt", O_CREAT | O_RDWR, 0664);
    if(fd == -1){
        perror("open file");
        exit(1);
    }

    //写入数据到打开的文件
    char buf[] = {"hello,linux,write!"};
    int count = write(fd, buf, sizeof(buf));
    if(count == -1){
        perror("write file");
        exit(1);
    }
    
    int length = lseek(fd, 0, SEEK_END); //设置文件指针到结尾,可以获取文件的当前大小
    if(length == -1){
        perror("lseek file");
        exit(1);
    }
    printf("before file length = %d\n", length);
    length = lseek(fd, 1000,SEEK_END); //拓展文件大小,当前文件指针位置为拓展前结尾位置+1000,1000为拓展量
    if(length == -1){
        perror("lseek file");
        exit(1);
    }
    printf("after file length = %d\n", length);
    write(fd, "zhang", 5);   //从当前文件指针位置,再写5个字节到文件
    length = lseek(fd, 0, 2);
    printf("file bytes: %d\n",length);
    close(fd);

    return 0;
}

结果:

before file length = 19
after file length = 1019
file bytes: 1024
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值