lseek 函数

	标准C库的函数
	    #include <stdio.h>
	    int fseek(FILE *stream, long offset, int whence);
	
	    Linux系统函数
	    #include <sys/types.h>
	    #include <unistd.h>
	    off_t lseek(int fd, off_t offset, int whence);
	        参数:
	            - fd:文件描述符,通过open得到的,通过这个fd操作某个文件
	            - offset:偏移量
	            - whence:
	                SEEK_SET
	                    设置文件指针的偏移量
	                SEEK_CUR
	                    设置偏移量:当前位置 + 第二个参数offset的值
	                SEEK_END
	                    设置偏移量:文件大小 + 第二个参数offset的值
	        返回值:返回文件指针的位置


    作用:
        1.移动文件指针到文件头
        lseek(fd, 0, SEEK_SET);

        2.获取当前文件指针的位置
        lseek(fd, 0, SEEK_CUR);

        3.获取文件长度
        lseek(fd, 0, SEEK_END);

        4.拓展文件的长度,当前文件10b, 110b, 增加了100个字节
        lseek(fd, 100, SEEK_END)
        注意:需要写一次数据
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main() {

    int fd = open("hello.txt", O_RDWR);
    if(fd == -1){
        perror("open1");
        return -1;
    }

    //扩展文件的长度
    int ret = lseek(fd, 100, SEEK_END);
    if(ret == -1){
        perror("open2");
        return -1;
    }
    //写入空数据
    write(fd, " ", 1);
    //关闭文件
    close(fd);
    return 0;
}

在这里插入图片描述

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值