linux下如何通过lseek定位大文件

背景:

    有一张16GB SD卡,插入开发板SD卡插槽,通过二进制方式向里面写入数据,在通过lseek()函数定位时返回-1,(本意是通过lseek()获取SD卡大小)代码如下:

large_sd.c

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

int main(int argc, char *argv[])
{

    long max_seek = 0;

    int fd = open("/dev/mmcblk0",O_RDWR);
    if(fd < 0)
    {
      printf("open file error.\n");  
      return -1;
    }
    max_seek = lseek(fd,0,SEEK_END);

    printf("MAX SEEK = %ld\n",max_seek);
    return 0;
}


编译: powerpc-linux-gcc -o large_sd large_sd.c

在开发板上执行,打印结果:

MAX SEEK = -1


后来通过搜索发现,原来是lseek()溢出所致,修改代码如下:

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

int main(int argc, char *argv[])
{

   long long max_seek = 0;

    int fd = open("/dev/mmcblk0",O_RDWR);
    if(fd < 0)
    {
        printf("open file error.\n");
        return -1;
    }
    max_seek = lseek(fd,0,SEEK_END);

    printf("MAX SEEK = %lld\n",max_seek);
    return 0;
}

编译: powerpc-linux-gcc -D_FILE_OFFSET_BITS=64 -o large_sd large_sd.c

再次在开发板上执行:

MAX SEEK = 15707668480

成功。


总结:

1.如果通过lseek()定位大文件,返回值需要使用long long型变量接收,以防止溢出。

2.编译时要加选项-D_FILE_OFFSET_BITS=64来定义_FILE_OFFSET_BITS为64

3.printf使用%lld来打印long long int 型。



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值