-
Notifications
You must be signed in to change notification settings - Fork 2
/
can2c.cc
67 lines (58 loc) · 1.46 KB
/
can2c.cc
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
#include <stdio.h> // fprintf
#include <stdlib.h> // exit
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "Usage: can2c .h lib/script.can [build/script.h]\n");
exit(1);
}
// Open both files
FILE* in = fopen(argv[1], "r");
if (in == NULL) {
fprintf(stderr, "Can\'t open input file: %s\n", argv[1]);
exit(1);
}
FILE* out;
if (argc >= 3) {
out = fopen(argv[2], "w");
if (out == NULL) {
fclose(in);
fprintf(stderr, "Can\'t open output file: %s\n", argv[2]);
exit(1);
}
} else {
out = stdout;
}
// Replace non-chars with _ in input filename
// and '.' with '\0'
for (int i = 0; argv[1][i] != 0; i++) {
unsigned char c = argv[1][i];
if (c == '.') {
argv[1][i] = 0;
break;
} else if (c < 'a' || c > 'z') {
argv[1][i] = '_';
}
}
// Put generated content into the output file
fprintf(out, "extern const char __binding_%s[] = {\n", argv[1]);
int offset = 0;
while (!feof(in)) {
// Read file
unsigned char buffer[1024];
size_t read = fread(buffer, 1, sizeof(buffer), in);
if (read == 0) {
fclose(in);
fclose(out);
fprintf(stderr, "Failed to read input file\n");
exit(1);
}
// Translate it to byte sequence
for (size_t i = 0; i < read; i++) {
fprintf(out, "0x%.2x, ", buffer[i]);
if (++offset % 30 == 0) fprintf(out, "\n");
}
}
fprintf(out, "0x0\n};");
fclose(in);
fclose(out);
}