二进制文件转化成数组

把一个二进制文件转换为c语言数组:

#include "stdafx.h"
#include <time.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h> 
#include "string.h"

unsigned int GetFileSize(char *filename);
void read_src(char *path, unsigned char *buf, unsigned int size);
void make_dstfile(char *outpath, unsigned char *buf, unsigned int size);

int main()
{


unsigned char *buf = NULL;


unsigned int size;
char srcbmp[100]={0};
char dstfile[100]={0};
//char srcbmp[100]="test.bin";
//char dstfile[100]="test.h";
printf("Please input src file name\nC file path name\n");
scanf("%s %s",srcbmp,dstfile);
size = GetFileSize(srcbmp);
buf = (unsigned char *)malloc(sizeof(unsigned char)*size);


read_src(srcbmp, buf, size);

make_dstfile(dstfile, buf, size);





	return 0;
}
unsigned int GetFileSize(char *filename)
{   
	unsigned int  siz = 0;   
	FILE  *fp = fopen(filename, "rb");   
	if (fp) 
	{      
		fseek(fp, 0, SEEK_END);      
		siz = ftell(fp);      
		fclose(fp);   
	}   
	return siz;
}

void read_src(char *path, unsigned char *buf, unsigned int size)
{
	FILE *infile;
	
	if((infile=fopen(path,"rb"))==NULL)
	{
		printf( "\nCan not open the path: %s \n", path);
		exit(-1);
	}

	fread(buf, sizeof(unsigned char), size, infile);//printf("\n打开的图为 %d",img->bfType);
	
	fclose(infile);
}
void make_dstfile(char *outpath, unsigned char *buf, unsigned int size)
{
	FILE *infile;
	int i,j,k,n;
	char pbuf[10]={0};
	if((infile=fopen(outpath,"wa+"))==NULL)
	{
		printf( "\nCan not open the path: %s \n", outpath);
		exit(-1);
	}
	k=0;

	fwrite("u8 temp_array[] = {\n",strlen("u8 m_firmware_data_200[] = {\n"),1,infile);
	for(i = 0; i < size; i++)
	{
			k++;
			sprintf(pbuf,"0x%02x",buf[i]);
			fwrite(pbuf,strlen(pbuf),1,infile);
			if(k != 8)
			fwrite(", ",strlen(", "),1,infile);
			else
			fwrite(",",strlen(","),1,infile);	
		
			if(k==8)
			{
				k=0;
				fwrite("\n",strlen("\n"),1,infile);

			}
		
	}

	fseek(infile,0,SEEK_END);
	if(k == 0)
		fwrite("};",strlen("};"),1,infile);
	else
		fwrite("\n};",strlen("\n};"),1,infile);


	fclose(infile);
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值