Linux系统编程——文件编程(四)光标移动(lseek)

lseek函数

lseek是一个用于改变读写一个文件时读写指针位置的一个系统函数

每个打开的文件都有一个与其相关联的“当前文件偏移量”,它通常是一个非负整数,用以度量从文件开始处计算的字节数。通常,读、写操作都从当前文件偏移量处开始,并使偏移量增加所读写的字节数。

头文件

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

函数原型

off_t lseek(int fd, off_t offset, int whence);

参数

int fd : 文件描述符
off_t offset : 相对于whence的偏移值,负数表示向左,正数表示向右,0表示原地
int whence : 固定点的位置

whence 有三个固定的宏:
在这里插入图片描述

lseek(fd,0,SEEK_SET)//相对于文件头偏移0,固定到头
lseek(fd,0,SEEK_CUR)//相对于文件当前位置偏移0,固定到当前位置
lseek(fd,0,SEEK_SET)//相对于文件最后偏移0,固定到最后

返回值

当调用成功则返回目前的读写位置,也就是当前位置距离文件开头有多少个字节,如果有错误则返回 -1

在这个代码中

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
    int fd;
    char* buf = "hello world!";
    char* readBuf = NULL;

    fd = open("./file2",O_RDWR);                                                                                             
    printf("creat file2 success %d\n",fd);

    int n_write = write(fd,buf,strlen(buf));        
    printf("write %d\n",n_write);          //打印写入到file2的字节个数

    //close(fd);                                //关闭文件
    //fd = open("./file2",O_RDWR);      //重新打开,让光标回到头,不然读不到数据
    lseek(fd,0,SEEK_SET);
    readBuf = (char*)malloc(sizeof(char) * n_write); //为readBuf开辟空间 
    int n_read = read(fd,readBuf,n_write);            //fd指向的文件读到readBuf中
    printf("readNum %d n_read = %s\n",n_read,readBuf); //打印读取到的字节个数和读到的数据

    close(fd);
    return 0;
}

在这里插入图片描述
可以看到利用lseek函数实现了将光标从字符串的最后移动到了最前面,当然,也可以将文件先关闭,再打开也可以将光标移动到最前面(这里如果不移动光标的话会读不到数据)。

利用lseek函数计算文件的字节数

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    int fd;
    int lseekNum = 0;
    fd = open("./file2",O_RDWR);
    lseekNum = lseek(fd,0,SEEK_END);
    printf("file2 size %d\n",lseekNum);
    close(fd);
    return 0;
}

在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值