-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcembed.c
76 lines (68 loc) · 1.63 KB
/
cembed.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getFilename(char *outName, const char *name, size_t size) {
char c;
int i = size;
int count = 0;
for (size; i > 0; i--) {
c = *(name + i);
if (c == '/') {
i++;
break;
}
count++;
}
memcpy(outName, name + i, count);
}
void replaceChar(char *name, char find, char replace) {
char *ret = strchr(name, find);
while(ret) {
*ret = replace;
ret = strchr(name, find);
}
}
int main(int argc, char ** argv) {
char path[128];
if (argc < 2) {
printf("usage: embed filename\n");
return 0;
}
FILE *fp;
fp = fopen(argv[1], "rb");
getFilename(path, argv[1], strlen(argv[1]));
replaceChar(path, '.', '_');
size_t size;
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
unsigned char buffer[size];
int sread = fread(buffer, 1, size, fp);
if (sread != size) {
printf("failed to read '%s'\n", argv[1]);
fclose(fp);
return 0;
}
size_t ssize = size * 20 + 512;
char out[ssize];
memset(out, 0, ssize);
sprintf(out, "static const unsigned char %s[] = {\n", path);
for (int i = 0; i < size; i++) {
if (buffer[i] == EOF) break;
char c[10];
sprintf(c, "%d,", buffer[i]);
sprintf(out, "%s%s", out, c);
if (i != 0 && i % 20 == 0) sprintf(out, "%s\n", out);
}
char end[256];
sprintf(end, "10};\nint %s_size = %d;", path, size);
int s = strlen(out) + strlen(end);
char oout[s];
sprintf(oout, "%s%s", out, end);
char outPath[512];
sprintf(outPath, "%s.h", argv[1]);
fp = fopen(outPath, "wb");
int swrite = fwrite(oout, s, 1, fp);
fclose(fp);
return 0;
}