linux下操纵大于2G文件

要点是编译时候加-D_FILE_OFFSET_BITS=64宏,程序中把使用fseek,ftell的地方分别换成fseeko,ftello。

-----------------------------------------------------

man fseeko

DESCRIPTION
The fseeko() and ftello() functions are identical to fseek() and ftell() (see fseek(3)), respectively, except that the offset argument of fseeko() and the return value of ftello() is of type off_t instead of long.

On many architectures both off_t and long are 32-bit types, but compilation with

#define _FILE_OFFSET_BITS 64

will turn off_t into a 64-bit type.

-----------------------------------------------------

编译方法:

#!/bin/sh

arm-mv5sft-linux-gnueabi-gcc -D_FILE_OFFSET_BITS=64 main.c -o test
gcc -D_FILE_OFFSET_BITS=64 main.c -o x86test

源程序:

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

#define FILENAME "10G.img"
#define READBUFSIZE 100
int main()
{
    printf("sizeof(size_t) %d, sizeof(off_t) %d\n", sizeof(size_t), sizeof(off_t));
    struct stat buf;
    if(stat(FILENAME, &buf)!=0)
    {
        perror("stat:");
        return -1;   
    }
    printf("%lld\n", buf.st_size);

    FILE *stream = fopen(FILENAME, "rw");
    if(!stream)
    {
        perror("fopen:");
        return -1;   
    }
    char readbuf[READBUFSIZE];

    {
        size_t ret = fread(readbuf, READBUFSIZE, 1, stream);
        printf("fread:%u\n", ret);
        assert(ret==1);
    }
    printf("%lld\n", ftello(stream));
    if(fseeko(stream, -100, SEEK_END)!=0)
    {
        perror("fseeko:");
        return -1;   
    }

    {
        size_t ret = fread(readbuf, READBUFSIZE, 1, stream);
        printf("fread:%u\n", ret);
        assert(ret==1);
    }

    printf("%lld\n", ftello(stream));

    return 0;
}

 

运行结果:

/mnt/DISKA/PARTITION1 # ./test
sizeof(size_t) 4, sizeof(off_t) 8
10485760000
fread:1
100
fread:1
10485760000

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值