最近工作上有从整个flash镜像中截取某一段的需求,在网上找了一圈没找到好用的工具,于是自己写了一个小工具,在linux上编译一下即可使用,源码如下,使用方法见文章末尾。
#include <stdio.h>
#include <stdlib.h>
unsigned long simple_strtoul(const char *cp,char **endp,unsigned int base)
{
unsigned long result = 0,value;
if (*cp == '0') {
cp++;
if ((*cp == 'x') && isxdigit(cp[1])) {
base = 16;
cp++;
}
if (!base) {
base = 8;
}
}
if (!base) {
base = 10;
}
while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp)
? toupper(*cp) : *cp)-'A'+10) < base) {
result = result*base + value;
cp++;
}
if (endp)
*endp = (char *)cp;
return result;
}
int main(int argc, char **argv)
{
if(argc !=5 )
{
printf("usage : originalFile cuttedFile startAddr cutSize\r\n");
printf("\t\tflash_filename \tthe name of original file\r\n");
printf("\t\tnew_filename \tthe name of cutted file\r\n");
printf("\t\tstartAddr \tthe start of file, hex value, eg:0x10000\r\n");
printf("\t\tcutSize \tthe size of file for cutting, hex value, eg:0x10000\r\n");
return 0;
}
FILE *original_file_fp = fopen(argv[1], "r+");
FILE *cutted_file_fp = fopen(argv[2], "w+");
int start_addr = simple_strtoul(argv[3], NULL, 16);
int cut_size = simple_strtoul(argv[4], NULL, 16);
fseek(original_file_fp, start_addr, SEEK_SET );
for(int i = 0; i < cut_size; ++i)
{
char c = fgetc(original_file_fp);
fputc(c, cutted_file_fp);
}
fclose(original_file_fp);
fclose(cutted_file_fp);
return 0;
}
新建main.c,将上面的代码复制到里面再编译一下即可:
gcc main.c -o cut_file
使用方法比较简单,例如,如果想从flash.bin中的0x100000开始,截取0xa00000长度的数据,保存到image1.bin当中,可按照下列命令进行截取。
./cut_file flash.bin image1.bin 0x100000 0xa00000
ps:解析十六进制表示的字符串的simple_strtoul函数是从内核里面扒出来的,不是自己写的。