How to write binary data for 7z archive format?

I spilled the format description and source code for 7z format, but I still cannot write a valid container. I suppose I can create an empty container ... anyway here is my start:

std::ofstream ofs(archivename.c_str(), std::ios::binary|std::ios::trunc);

Byte signature[6] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
Byte major = 0;
Byte minor = 3;

ofs.write((const char*)signature, 6);
ofs.write((const char*)major, 1);
ofs.write((const char*)minor, 1);

UInt64 offset = 0;
UInt64 size = 0;
UInt32 crc = 0;

ofs.write((const char*)offset, 4);
ofs.write((const char*)size, 8);
ofs.write((const char*)crc, 8);
ofs.write((const char*)CrcCalc(0, 0), 8);

ofs.close();

I think my main problem is the lack of understanding of std :: ofstream :: write (). A byte is an unsigned char, UInt64 and UInt32 are both unsigned.

UPDATE0 . As everyone points out, that would be a problem if I ran it on a big end machine. This is not true. Per Fredrik Janssen, I have to specify the address of non-arrays. It should also be mentioned that CrcCalc () is a function in the LZMA SDK. By adding and helping a bit, this is the first unsigned char [6] having some problems.

UPDATE1: , .

static void SetUInt32(Byte *p, UInt32 d)
{
  for (int i = 0; i < 4; i++, d >>= 8)
    p[i] = (Byte)d;
}

static void SetUInt64(Byte *p, UInt64 d)
{
  for (int i = 0; i < 8; i++, d >>= 8)
    p[i] = (Byte)d;
}

void make_7z_archive()
{
  CrcGenerateTable();

  std::ofstream ofs(archivename.c_str(), std::ios::binary|std::ios::trunc);

  Byte signature[6] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};
  Byte major = 0;
  Byte minor = 3;

  ofs.write((const char*)signature, 6);
  ofs.write((const char*)&major, 1);
  ofs.write((const char*)&minor, 1);

  UInt64 offset = 0;
  UInt64 size = 0;
  UInt32 crc = 0;

  Byte buf[24];
  SetUInt64(buf + 4, offset);
  SetUInt64(buf + 12, size);
  SetUInt32(buf + 20, crc);
  SetUInt32(buf, CrcCalc(buf + 4, 20));

  ofs.write((const char*)buf, 24);

  ofs.close();
}

: CrcGenerateTable() CrcCalc() SDK LZMA.

+3
2

7z, , , crc, little-endian ( , -endian CPU).

: , , , , , crc, .. .

+2

-... . SDK... ... 7-zip- . . p7zip SourceForge. p7zip, , "7z", , .

7z ( /GUI ), , SDK? ( LGPL)

0

Source: https://habr.com/ru/post/1702486/


All Articles