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

原文地址:https://www.cnblogs.com/cute/p/2112621.html