[C/C++ 演算法] 實作任裡兩個檔案合併與分開(自己實作檔案簡易打包)
[C/C++ 演算法] 實作任裡兩個檔案合併與分開(自己實作檔案簡易打包)
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct Data
{
char file1[256];
long file1_size;
char file2[256];
long file2_size;
char outfile[256];
};
bool MakeCustomCAB(Data *dat)
{
cout << dat->file1<< endl;
cout << dat->file2<< endl;
cout << dat->outfile<< endl;
//file size
FILE *pf1 = fopen(dat->file1,"rb");
if ( NULL == pf1 )
{
return false;
}
fseek(pf1, 0L, SEEK_END);
dat->file1_size = ftell(pf1);
cout << dat->file1 <<" size="<<dat->file1_size<< endl;
fclose(pf1);
FILE *pf2 = fopen(dat->file2,"rb");
if ( NULL == pf2 )
{
return false;
}
fseek(pf2, 0L, SEEK_END);
dat->file2_size = ftell(pf2);
cout << dat->file2 <<" size="<<dat->file2_size<< endl;
fclose(pf2);
//
FILE *pOutFile = fopen(dat->outfile,"wb");
if ( NULL == pOutFile )
{
return false;
}
//¼g¤J¤å¥óÀY
fwrite(dat,sizeof(Data),1,pOutFile);
FILE *pWorkFile1;
for(int i=0;i<2;i++)
{
if(i==0)
pWorkFile1 = fopen(dat->file1,"rb");
else
pWorkFile1 = fopen(dat->file2,"rb");
if ( NULL == pWorkFile1 )
{
fclose(pWorkFile1);
fclose(pOutFile);
return false;
}
unsigned char *pTmpData1 = NULL;
pTmpData1 = new unsigned char[dat->file1_size];
fread(pTmpData1,dat->file1_size,1,pWorkFile1);
if ( ferror(pWorkFile1) )
{
fclose(pWorkFile1);
fclose(pOutFile);
return false;
}
fwrite(pTmpData1,dat->file1_size,1,pOutFile);
if ( ferror(pOutFile) )
{
fclose(pWorkFile1);
fclose(pOutFile);
return false;
}
delete [] pTmpData1;
pTmpData1=NULL;
fclose(pWorkFile1);
pWorkFile1=NULL;
}
fclose(pOutFile);
return true;
}
void DoUnCAB(char *CabFilePathName)
{
FILE *pCAB = NULL;
FILE *pWork = NULL;
pCAB = fopen(CabFilePathName,"rb");
//讀文件頭
Data dat;
memset(&dat,0x0,sizeof(Data));
fread(&dat,sizeof(Data),1,pCAB);
cout << dat.file1<< endl;
cout << dat.file2<< endl;
cout << dat.outfile<< endl;
//printCAB();
//解包的所有檔放到當前目錄下
for ( int i = 0 ; i < 2 ; i++ )
{
unsigned char *pTmpData = NULL;
if(i==0)
{
pTmpData = new unsigned char[dat.file1_size];
fread(pTmpData,dat.file1_size,1,pCAB);
pWork = fopen(dat.file1,"wb");
fwrite(pTmpData,dat.file1_size,1,pWork);
}
else
{
pTmpData = new unsigned char[dat.file2_size];
fread(pTmpData,dat.file2_size,1,pCAB);
pWork = fopen(dat.file2,"wb");
fwrite(pTmpData,dat.file2_size,1,pWork);
}
fclose(pWork);
delete [] pTmpData;
}
fclose(pCAB);
}
int main()
{
Data *dat;
dat=new Data[1];
cout << "Hello world!" << endl;
/*
strcpy(dat->file1,"c:\\b_xml1.xml");
strcpy(dat->file2,"c:\\b_xml2.xml");
strcpy(dat->outfile,"c:\\b_xml.xml");
MakeCustomCAB(dat);
*/
DoUnCAB("c:\\b_xml.xml");
return 0;
}