How to read and write a file

This topic describes how to reading transfer data from a file to a descriptor, and writing transfers data from a descriptor to a file.

Reading transfers data from a file to a descriptor, and writing transfers data from a descriptor to a file.

Use RFile::Read() to read, and RFile::Write() to write.

// Open file1
_LIT(KMyFile,"c:\\documents\\file1");
RFile myFile;
User::LeaveIfError(myFile.Open(fs,KMyFile,EFileShareExclusive|EFileWrite
));

// Write to current file position: start of file
_LIT8(KWriteBuf,"write data");
myFile.Write(KWriteBuf);

// Read from position 0: start of file
TBuf8<6> readBuf1;
myFile.Read(0,readBuf1); // readBuf1 is now "write "

// Read from current position
TBuf8<4> readBuf2;
myFile.Read(readBuf2);      // readBuf2 is now "data"

Notes

  • In all cases, the file data is treated as binary and byte descriptors are used (TDes8, TDesC8). Thus, file operations are not dependent on the Unicode/non-Unicode build variant.

  • There are several variants of both Read() and Write(). The basic Read(TDes8& aDes) and Write(const TDesC8& aDes) are supplemented by variants allowing the descriptor length to be overridden, or the seek position of the first byte to be specified, or asynchronous completion, or any combination.