/
mkresource.c
115 lines (93 loc) · 1.78 KB
/
mkresource.c
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Serge Voilokov, 2015
// Convert text file into C string.
// Creates pair of .h and .c files.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
static void
usage()
{
printf(
"usage: mkresource FILE\n"
"Converts text file to C string.\n"
"Produces .h and .c files pair.\n");
}
static const char *fname;
#define NSIZE 200
static char name[NSIZE];
static char h_fname[NSIZE+3];
static char c_fname[NSIZE+3];
static void
create_names()
{
const char *slash = strrchr(fname, '/');
if (slash != NULL)
slash++;
else
slash = fname;
strncpy(name, slash, NSIZE);
char *dot = strrchr(name, '.');
if (dot != NULL)
*dot = '_';
strncpy(h_fname, slash, NSIZE);
strcat(h_fname, ".h");
strncpy(c_fname, slash, NSIZE);
strcat(c_fname, ".c");
}
int main(int argc, char **argv)
{
if (argc < 2) {
usage();
exit(1);
}
FILE *fin, *fh, *fc;
fname = argv[1];
create_names();
fin = fopen(fname, "rt");
if (fin == NULL)
err(1, "cannot open input file: %s", fname);
fc = fopen(c_fname, "wt");
if (fc == NULL)
err(1, "cannot open output C file %s", c_fname);
fh = fopen(h_fname, "wt");
if (fh == NULL)
err(1, "cannot open output H file %s", h_fname);
fprintf(fh,
"extern const char %s[];\n"
"extern const size_t %s_size;\n",
name, name);
fprintf(fc,
"#include <unistd.h>\n"
"\n"
"const char %s[] = \"\"\n\"",
name);
int c = 0;
size_t size = 0;
while ((c = fgetc(fin)) != EOF) {
size++;
switch (c) {
case '\\':
fputs("\\\\", fc);
break;
case '\"':
fputs("\\\"", fc);
break;
case '\n':
fputs("\\n\"\n\"", fc);
break;
default:
fputc(c, fc);
}
}
fprintf(fc,
"\";\n"
"\n"
"const size_t %s_size = %zu;\n",
name,
size);
fclose(fc);
fclose(fh);
fclose(fin);
return 0;
}