summaryrefslogtreecommitdiff
path: root/scripts/bin2hex.c
blob: f7b9d8cf03d0761ef71820c2f60aedd5d922d2c6 (plain)
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
/* bin2hex.c -- Turn the contents of a file into an array of unsigned chars */

#include <stdio.h>
#include <string.h>

/* We never want to build memento versions of the cquote util */
#undef MEMENTO

static void
clean(char *p)
{
	while (*p)
	{
		if ((*p == '/') || (*p == '.') || (*p == '\\') || (*p == '-'))
			*p = '_';
		p ++;
	}
}

int
main(int argc, char **argv)
{
	FILE *fi, *fo;
	char name[256];
	char *realname;
	int i, j, c;

	if (argc < 3)
	{
		fprintf(stderr, "usage: bin2hex output.h lots of text files\n");
		return 1;
	}

	fo = fopen(argv[1], "wb");
	if (!fo)
	{
		fprintf(stderr, "cquote: could not open output file '%s'\n", argv[1]);
		return 1;
	}

	fprintf(fo, "/* This is an automatically generated file. Do not edit. */\n");

	for (i = 2; i < argc; i++)
	{
		realname = strrchr(argv[i], '/');
		if (!realname)
			realname = strrchr(argv[i], '\\');
		if (realname)
			realname ++;
		else
			realname = argv[i];

		if (strlen(realname) > (sizeof name - 1))
		{
			fprintf(stderr, "bin2hex: file name too long\n");
			if (fclose(fo))
			{
				fprintf(stderr, "bin2hex: could not close output file '%s'\n", argv[1]);
				return 1;
			}
			return 1;
		}

		strcpy(name, realname);
		clean(name);

		fi = fopen(argv[i], "rb");

		j = 0;
		while ((c = fgetc(fi)) != EOF)
		{
			if (j != 0)
			{
				fputc(',', fo);
				fputc(j%8 == 0 ? '\n' : ' ', fo);
			}

			fprintf(fo, "0x%02x", c);
			j++;
		}

		fputc('\n', fo);

		if (fclose(fi))
		{
			fprintf(stderr, "bin2hex: could not close input file '%s'\n", argv[i]);
			return 1;
		}

	}

	if (fclose(fo))
	{
		fprintf(stderr, "bin2hex: could not close output file '%s'\n", argv[1]);
		return 1;
	}

	return 0;
}