时间:2021-03-06 10:11:59 | 栏目:C代码 | 点击:次
#define MAXLEN 10240
void usage();
int main(int argc,char *argv[])
{
int count,packetLength,dataLength,olddataLength,datasum,line,remainder,*Length;
char *FILENAME,*OUTNAME;
char int2char[10];
unsigned char buffer[MAXLEN];
FILE *INFILE,*OUTFILE;
//获取输入的参数
if(argc == 1)
FILENAME="UPDATE.APP";
else
FILENAME=argv[1];
//用二进制打开输入文件
if((INFILE = fopen(FILENAME, "rb")) == NULL) usage();
//创建文件夹并进入目录
mkdir("output");
chdir("output");
//跳过92空字节
fseek(INFILE, 92, 0);
for(count=1;INFILE != NULL;count++)
{
//判断是否为华为固件索引头
fread(buffer, 4, 1, INFILE);
if(buffer[0] != 0x55) break;
if(buffer[1] != 0XAA) break;
if(buffer[2] != 0x5A) break;
if(buffer[3] != 0xA5) break;
//获取头文件长度
fread(buffer, 4, 1, INFILE);
Length = (int *)buffer;
packetLength=*Length;
//跳过16字节
fseek(INFILE, 16, 1);
//获取内容长度
fread(buffer, 4, 1, INFILE);
Length = (int *) buffer;
dataLength=*Length;
//把整数和字符串连接并复制给文件名
itoa(count, int2char, 10);
OUTNAME=strcat(int2char, ".img");
//跳到头文件末尾
fseek(INFILE, packetLength-28, 1);
//创建文件
if((OUTFILE = fopen(OUTNAME, "wb")) == NULL)
{
printf("Unrecognised file format. Wrong identifier.\n");
return -1;
} else printf("Extracted output/%s\n",OUTNAME);
//把内容数据分成多个部分
datasum=dataLength/MAXLEN;
for(line=0;line <= datasum;line++)
{
//获取内容数据
if(datasum == line)
fread(buffer, dataLength % MAXLEN, 1, INFILE);
else
fread(buffer, MAXLEN, 1, INFILE);
//输出文件
if(datasum == line)
fwrite(buffer, dataLength % MAXLEN, 1, OUTFILE);
else
fwrite(buffer, MAXLEN, 1, OUTFILE);
}
//关闭输出文件
fclose(OUTFILE);
//指针取整,4的倍数
remainder = 4 - (ftell(INFILE) % 4);
if (remainder < 4)
{
//进行填充剩余的字节
fseek(INFILE, remainder, 1);
}
}
//关闭输入文件
fclose(INFILE);
return 0;
}
void usage()
{
//帮助函数
printf("uasge: unpack_update.exe [UPDATE.APP|UPDATA.APP]\n");
exit(0);
}