In-Memory Archive Processing
Applies To: All

Introduction

In-Memory Archive Creating and Opening

To create or open an archive in memory, use the CZipArchive::Open(CZipAbstractFile&) method and pass CZipMemFile object as an argument.

Creating

If you are creating a new archive, the memory file will hold the resulting archive.
Sample Code
CZipMemFile mf;
CZipArchive zip;
// create the archive in memory
zip.Open(mf, CZipArchive::zipCreate);
// add a file
zip.AddNewFile(_T("C:\\Temp\\file.dat"));
zip.Close();
// let's write the archive to the disk
CZipFile f;
if (f.Open(_T("C:\\Temp\\test.zip"),
CZipFile::modeWrite | CZipFile::modeCreate, false))
{
int iLen = (int)mf.GetLength();
BYTE* b = mf.Detach();
f.Write(b, iLen);
f.Close();
// we must free the detached memory
free(b);
}

Opening

If you are opening an existing archive, the memory file should already hold an archive.
Sample Code
CZipFile f;
if (f.Open(_T("C:\\Temp\\test.zip"), CZipFile::modeRead, false))
{
// read the contents of the file into the memory file
int iLen = (int)f.GetLength();
BYTE* b = (BYTE*)malloc((UINT)iLen);
f.Read(b, iLen);
f.Close();
CZipMemFile mf;
mf.Attach(b, iLen);
// open the archive in memory
CZipArchive zip;
zip.Open(mf);
zip.ExtractFile(0, _T("C:\\Temp"));
zip.Close();
}

In-Memory Data Compressing and Extracting

Sample Code
LPCTSTR zipFileName = _T("C:\\Temp\\test.zip");
CZipArchive zip;
zip.Open(zipFileName, CZipArchive::zipCreate);
CZipMemFile mf;
// prepare the memory file
LPCTSTR data1 = _T("Test data");
mf.Write(data1, (DWORD)(_tcslen(data1) * sizeof(TCHAR)));
// compress the memory data
zip.AddNewFile(mf, _T("file1.txt"));
zip.Close();
zip.Open(zipFileName);
CZipMemFile mfOut;
// set the memory file size to the size of the uncompressed data to avoid
// frequent memory allocations
mfOut.SetLength(zip[0]->m_uUncomprSize);
((CZipAbstractFile*)&mfOut)->SeekToBegin(); // may be needed when mfOut was used previously
// extract the contents of the file into memory
zip.ExtractFile(0, mfOut);
zip.Close();
// print the contents of the extracted data
BYTE* b = mfOut.Detach();
_tprintf((LPCTSTR)b);
// we must free the detached memory
free(b);

See Also API Links

Article ID: 0610231924
Copyright © 2000 - 2022 Artpol Software - Tadeusz Dracz