-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSource210_image.c
More file actions
102 lines (80 loc) · 2.42 KB
/
Source210_image.c
File metadata and controls
102 lines (80 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define IMG_SIZE 16 * 1024
#define HEADER_SIZE 16
int
main(int argc,char *argv[])
{
unsigned char *ucBuffer;
FILE *pfile;
unsigned int binlen = 0;
unsigned int i;
unsigned int checksum = 0; /* 校检合 */
unsigned short buffer = 0; /* reading 1 byte from bl1 */
/* 判断输入是否合法 */
if(argc != 3){
printf("usage:%s <source file> <destination file>\n",argv[1]);
return -1;
}
/* 分配内存 */
ucBuffer = (unsigned char*)malloc(IMG_SIZE);
if(ucBuffer == NULL){
printf("malloc buffer error\n");
return -1;
}
/* 初始化内存 */
memset(ucBuffer,0,IMG_SIZE);
/* 打开bin文件 */
pfile = fopen(argv[1],"rb");
if(pfile == NULL){
printf("source file fopen error\n");
return -1;
}
/* 偏移指针移到文件尾并得到整个文件的长度 */
fseek(pfile,0,SEEK_END);
binlen = ftell(pfile);
/* 将偏移指设置到文件开头 */
fseek(pfile,0,SEEK_SET);
/* 文件长度不得超过(16kb-16)个字节 */
if(binlen > (IMG_SIZE - HEADER_SIZE)){
printf("source bin is > 16kByte\n");
fclose(pfile);
free(ucBuffer);
return -1;
}
/* read bin to memory */
if(fread(ucBuffer + HEADER_SIZE,1,binlen,pfile) != binlen){
printf("fread source bin error\n");
free(ucBuffer);
fclose(pfile);
return -1;
}
/* 关闭文件,不需要就关闭 */
fclose(pfile);
/* 求出校检合 */
for (i = 0; i < IMG_SIZE - HEADER_SIZE; i++) {
buffer = (*(volatile unsigned char*)(ucBuffer + HEADER_SIZE + i));
checksum += buffer;
}
binlen += HEADER_SIZE;
/* BL1 size */
*(volatile unsigned int*)ucBuffer = binlen;
/* 写进缓冲区 */
*(volatile unsigned int*)(ucBuffer + 8) = checksum;
if ((pfile = fopen(argv[2],"wb")) == NULL) {
printf("fopen file error");
free(ucBuffer);
return -1;
}
/* 写入文件中 */
if (fwrite(ucBuffer,1,binlen,pfile) != binlen) {
printf("file fwrite error\n");
free(ucBuffer);
fclose(pfile);
return -1;
}
free(ucBuffer);
fclose(pfile);
return 0;
}