两种将文件读入BUF的方法

// 方法1:使用RFileReadStream

TUint8* CUtil::ReadBufFromFileL( RFs& aFs, const TDesC& aFileName )

{

RFileReadStream readStream;

User::LeaveIfError(readStream.Open(aFs, aFileName, EFileShareReadersOnly | EFileStreamText | EFileRead));

CleanupClosePushL(readStream);

 

TInt nSize = readStream.Source()->SizeL();

if (nSize <= 0)

{

return NULL;

}

 

TUint8* pBuffer = new (ELeave) TUint8[nSize];

CleanupStack::PushL(pBuffer);

TPtr8 ptrBuffer(pBuffer, 0, nSize);

 

readStream.ReadL(ptrBuffer);

 

CleanupStack::Pop(pBuffer);

CleanupStack::PopAndDestroy(); // readStream

return pBuffer;

}

 

// 方法2:使用RFile

HBufC8* CUtil::ReadBufFromFileL( RFs& aFs, const TDesC& aFileName )

{

RFile file;

User::LeaveIfError(file.Open(aFs, aFileName, EFileShareReadersOnly | EFileRead));

TInt fileSize = 0;

file.Size(fileSize);

if(fileSize <= 0)

{

return NULL;

}

 

HBufC8* fileBuffer = HBufC8::NewL(fileSize + 4);

TPtr8 ptrFileBuffer = fileBuffer->Des();

file.Read(0, ptrFileBuffer, fileSize);

 

file.Close();

return fileBuffer;

}

你可能感兴趣的:(两种将文件读入BUF的方法)