我一直在傾注7z歸檔格式的格式描述和源代碼,但我仍然無法編寫有效的容器。我以爲我可以創建一個空的容器......反正這是我的起點:如何編寫7z歸檔格式的二進制數據?
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();
我想我的主要問題是缺乏的std :: ofstream的認識::寫()。字節是'無符號字符',UInt32都是'無符號長'。
UPDATE0:正如大家指出的那樣,如果我在大型機器上運行它,會是一個問題。情況並非如此。 Per Fredrik Janssen,我應該投射非數組的地址。我還應該提到CrcCalc()是LZMA SDK中的一個函數。添加&有點幫助,這是第一個無符號字符[6],它有一些問題。
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()來自LZMA SDK。
只注意到&我自己。該格式是小端,我在一個小端CPU ...我稍後會擔心可移植性。 ;) – 2009-01-30 16:58:10
缺少&符號是問題所在。另外,我將其他值填入緩衝區數組中,遵循7z源代碼中的示例。謝謝你的額外的眼睛。 – 2009-01-30 17:13:53