Posted on 2010-12-13 22:30
魔のkyo 阅读(493)
评论(4) 编辑 收藏 引用
template<typename T>
T SwapByte(const T& v)
{
T res = v;
char* p = (char*)&res;
char* q = (char*)&res+sizeof(T)-1;
while(p<q)
{
swap(*p,*q);
p++;
q--;
}
return res;
}
template<typename T>
T DoNothing(const T& v)
{
return v;
}
struct PkgNode
{
char* m_Filename; //4
void* m_pData; //4
size_t m_Size; //4
}; // 12
void WritePkg(const char* filename, PkgNode pkgNodes[], int n)
{
FILE* fp = fopen(filename, "wb");
// offset 0
{ //写头
char head[12] = "DAISPKG";
fwrite(head, 12, 1, fp);
}
// offset 12
{ //写Endian标志
int endianFlag = 0x12345678;
fwrite(&endianFlag, 4, 1, fp);
}
// offset 16
{ //写入文件个数
fwrite(&n, 4, 1, fp);
}
// offset 20
{ //留白
int x = 0;
fwrite( &x, sizeof(PkgNode), n, fp);
}
// offset 20 + sizeof(PkgNode) * n
PkgNode* pkgHeader = (PkgNode*)malloc(sizeof(PkgNode)*n);
for(int i=0;i<n;i++)
{
pkgHeader[i].m_Filename = (char*)ftell(fp);
fwrite(pkgNodes[i].m_Filename, strlen(pkgNodes[i].m_Filename)+1, 1, fp);
}
for(int i=0;i<n;i++)
{
pkgHeader[i].m_pData = (void*)ftell(fp);
fwrite(pkgNodes[i].m_pData, pkgNodes[i].m_Size, 1, fp);
pkgHeader[i].m_Size = pkgNodes[i].m_Size;
}
fseek(fp, 20, SEEK_SET);
fwrite(pkgHeader, sizeof(PkgNode)*n, 1, fp);
free(pkgHeader);
fclose(fp);
}
void* ReadPkg(const char* filename, PkgNode** pkgNodes, int* n)
{
FILE* fp = fopen(filename, "rb");
fseek(fp, 0, SEEK_END);
size_t size = ftell(fp);
fseek(fp, 0, SEEK_SET);
void* pData = malloc(size);
fread(pData, size, 1, fp);
char head[12] = "DAISPKG";
if(memcmp(head, pData, 12)==0)
{
int endianFlag = *(int*)((char*)pData + 12);
int (*EndianProc)(const int&) = NULL;
if(endianFlag==0x12345678)
{
EndianProc = DoNothing<int>;
}
else
{
//endianFlag should be 0x78563412
EndianProc = SwapByte<int>;
}
int fileNum = EndianProc(*(int*)((char*)pData + 16));
*n = fileNum;
*pkgNodes = (PkgNode*)((char*)pData + 20);
for(int i=0;i<fileNum;i++)
{
(*pkgNodes)[i].m_Filename = (char*)(EndianProc((int)((*pkgNodes)[i].m_Filename)) + (int)pData);
(*pkgNodes)[i].m_pData = (void*)(EndianProc((int)((*pkgNodes)[i].m_pData)) + (int)pData);
}
}
else
{
free(pData);
pData = NULL;
}
fclose(fp);
return pData;
}
void ReleasePkg(void* ptr)
{
free(ptr);
}