Reading from Large Files

How to read from large files.

Introduction

Files can be read from their current position or from a specified position. The procedure is the same in both cases:

  1. Replace RFile with RFile64.

    //RFile file;
    RFile64 file;
  2. Use a TInt64 to specify the position to start reading from.

    The TInt variable in the example below has been replaced with a TInt64 to read from locations beyond 2GB–1 in large files.

    // TInt readPosition = 0;
    TInt64 readPosition = 0

Read() from relative/current position

Example

Modify applications to handle reads beyond 2GB–1. For example, a counter variable accumulating the number of bytes should be of type TInt64. The counter variable bytesRead in the example below is now a TInt64.

    // RFile file;
    RFile64 file;
    TInt err = file.Open(TheFs, _L(“BIGFILE.BIG”), EFileRead);
    if(err != KErrNone)
     {
        // handle unrelated error
        return err;
     }

    // Large file access is now supported!

    // Replace TInt variable with TInt64 variable
    // Tint bytesRead = 0;
    TInt64 bytesRead = 0;
    TBuf8<4096> readBuf;
    ...
    // Read loop
    FOREVER
        {
        // Read a block
        r = file.Read(readBuf);
        if(KErrNone != r)
            {
            // Error handling
            break;
            }
        bytesRead += readBuf.Length(); // bytesRead can exceed 2G as large files are now supported

Read() from absolute position

Example

To read locations beyond 2GB–1 in large files the file must be opened for 64-Bit access and the TInt variable should be replaced with a TInt64 variable or specify the position value directly.

//    RFile file;
    RFile64 file;
    TInt err = file.Open(TheFs, _L(“BIGFILE.BIG”), EFileRead);
    if(err != KErrNone)
     {
        // handle unrelated error
        return err;
     }

    // Large file access is now supported!
    // TInt readPosition = 0;
    TInt64 readPosition = 0;    // Use a TInt64 to prevent wrap-around
    TBuf8<4096> readBuf;
    ...
    // Read loop
    FOREVER
        {
        // Read a block
        r = file.Read(readPosition, readBuf);
        if(KErrNone != r)
            {
            // Error handling
            break;
            }
        readPosition += readBuf.Length();        // Must use TInt64 read position
        }