ctpv/embed/embed.c

96 lines
1.7 KiB
C
Raw Normal View History

2022-05-22 09:55:04 +02:00
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>
void getvarname(char *res, char *prefix, char *filename)
{
char *s = strrchr(filename, '/');
if (s)
s++;
else
s = filename;
if (prefix) {
size_t prefix_len = strlen(prefix);
memcpy(res, prefix, prefix_len);
res += prefix_len;
}
2022-05-23 03:27:10 +02:00
int c, i = 0;
for (; s[i] != 0; i++) {
2022-05-22 09:55:04 +02:00
c = s[i];
if (!isalnum(c))
c = '_';
res[i] = c;
}
2022-05-23 03:27:10 +02:00
res[i] = '\0';
}
void print_byte(char c)
{
printf("0x%x, ", c);
2022-05-22 09:55:04 +02:00
}
2022-05-23 03:27:10 +02:00
void print_file(char *f)
2022-05-22 09:55:04 +02:00
{
2022-05-23 03:27:10 +02:00
int c;
FILE *file = fopen(f, "r");
if (!file) {
fprintf(stderr, "failed to open %s: %s\n", f, strerror(errno));
2022-05-22 09:55:04 +02:00
exit(EXIT_FAILURE);
}
2022-05-23 03:27:10 +02:00
while ((c = fgetc(file)) != EOF)
print_byte(c);
fclose(file);
}
void embed_file(char *prefix, char *filename, char *helpers)
{
2022-05-22 09:55:04 +02:00
static char varname[FILENAME_MAX];
2022-05-23 21:39:01 +02:00
2022-05-22 09:55:04 +02:00
getvarname(varname, prefix, filename);
printf("char %s[] = { ", varname);
2022-05-23 03:27:10 +02:00
if (helpers) {
print_file(helpers);
print_byte('\n');
}
2022-05-22 09:55:04 +02:00
2022-05-23 03:27:10 +02:00
print_file(filename);
2022-05-22 09:55:04 +02:00
2022-05-23 03:27:10 +02:00
puts("0 };");
2022-05-22 09:55:04 +02:00
}
int main(int argc, char *argv[])
{
2022-05-23 03:27:10 +02:00
char *prefix = NULL, *helpers = NULL;
2022-05-22 09:55:04 +02:00
int c;
2022-05-23 03:27:10 +02:00
while ((c = getopt(argc, argv, "p:h:")) != -1) {
2022-05-22 09:55:04 +02:00
switch (c) {
case 'p':
prefix = optarg;
break;
2022-05-23 03:27:10 +02:00
case 'h':
helpers = optarg;
break;
2022-05-22 09:55:04 +02:00
default:
return EXIT_FAILURE;
}
}
for (int i = optind; i < argc; i++)
2022-05-23 03:27:10 +02:00
embed_file(prefix, argv[i], helpers);
2022-05-22 09:55:04 +02:00
return EXIT_SUCCESS;
}