linux下操縱大於2G檔案

來源:互聯網
上載者:User

要點是編譯時間候加-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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.