Чтобы скопировать содержимое файла на диске в буфер памяти, управляемый экземпляром CMemFile
, необходимо выполнить следующие шаги:
- Открыть файл на диске, передав правильные параметры.
- Выделите память для использования экземпляром
CMemFile
. - Считайте содержимое диска в буфер памяти, контролируемый
CMemFile
.
Ниже приведена возможная реализация:
// Open file on disk
// typeBinary is necessary to read the raw, untransformed contents
// shareDenyWrite is required to prevent the file from changing in between querying
// its size and reading the contents
// osSequentialScan could be used to provide an access pattern hint to the OS
// to allow it to better optimize the (potentially slow) disk accesses
CFile File( L"C:\\test.txt", CFile::modeRead | CFile::typeBinary | CFile::shareDenyWrite );
auto Length = File.GetLength();
// Construct CMemFile instance and allocate memory
CMemFile memFile();
auto buffer = memFile.Alloc( Length );
if ( !buffer ) {
// Depending on your exception handling system, call AfxThrowMemoryException instead
throw std::bad_alloc();
}
// Transfer ownership of the buffer to the CMemFile instance
memFile.Attach( buffer, Length );
// Read contents into memory buffer
// Note, that this is limited to file sizes smaller than 4 GB
File.Read( buffer, static_cast<UINT>( Length ) );
В этот момент все содержимое файла диска было считано в буфер CMemFile
instance ', при условии, что по пути не возникло никаких исключений.Все ресурсы контролируются объектами C ++, и ручная очистка не требуется.Когда объект memFile
выходит из области видимости, его память автоматически освобождается.Когда экземпляр File
выходит из области видимости, файл системного уровня HANDLE
закрывается.