Providing Custom Data: Extra Fields
Applies To: All

Introduction

Writing Local Extra Field

You can specify local extra fields only when creating a new file in an archive, because the local header is written at that time. You need to:
Sample Code
    // define your id
    const WORD id = 0xABCD;
    CZipArchive zip;    
    zip.Open(_T("C:\\Temp\\test.zip"), CZipArchive::zipCreate);
    // prepare a template of the file to add
    CZipFileHeader templ;
    templ.SetFileName(_T("file.dat"));
    // create a local extra field
    CZipExtraData* extra = templ.m_aLocalExtraData.CreateNew(id);
    // copy some data to the extra field
    const char* data = "data to save";
    size_t dataSize = strlen(data);
    extra->m_data.Allocate((DWORD)dataSize);
    memcpy(extra->m_data, data, dataSize);
    // for simplicity, create an empty file
    zip.OpenNewFile(templ);
    zip.CloseNewFile();
    zip.Close();

Writing Central Extra Field

Sample Code
    // define your id
    const WORD id = 0xABCD;
    CZipArchive zip;    
    // open an existing file
    zip.Open(_T("C:\\Temp\\test.zip"));
    // create a new central extra field
    CZipExtraData* extra = zip[0]->m_aCentralExtraData.CreateNew(id);
    // copy some data to the extra field
    const char* data = "data to save";
    size_t dataSize = strlen(data);
    extra->m_data.Allocate((DWORD)dataSize);
    memcpy(extra->m_data, data, dataSize);
    // resave the central directory
    zip.RemoveCentralDirectoryFromArchive();
    zip.Close();

Reading Extra Fields

Sample Code
    // define your id
    const WORD id = 0xABCD;
    CZipArchive zip;    
    // open an existing file
    zip.Open(_T("C:\\Temp\\test.zip"));
    const int index = 0;
    // update the local header
    // it would already be valid, if the file was
    // extracted before
    zip.OpenFile(index);
    zip.CloseFile();
    const CZipFileHeader* info = zip[index];
    // read local header
    CZipExtraData* extra = info->m_aLocalExtraData.Lookup(id);
    if (extra != NULL)
    {
        // ... process data
    }
    extra = info->m_aCentralExtraData.Lookup(id);
    if (extra != NULL)
    {
        // ... process data
    }
    zip.Close();
Article ID: 0610242300
Copyright © 2000 - 2009 Artpol Software - Tadeusz Dracz