文件截取小工具

最近工作上有从整个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函数是从内核里面扒出来的,不是自己写的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值