summaryrefslogtreecommitdiff
path: root/etc/bin2c.c
blob: fca82a556d16bf5b2ba2000efb9510f175c9f89a (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
/*
* bin2c.c
* convert binary files to byte arrays
* Luiz Henrique de Figueiredo (lhf@tecgraf.puc-rio.br)
* 24 Nov 98 12:15:27
*/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

void dump(FILE* f, int n)
{
 printf("static unsigned char B%d[]={\n",n);
 for (n=1;;n++)
 {
  int c=getc(f); 
  if (c==EOF) break;
#if 0
  printf("0x%02x,",c);
#else
  printf("%3u,",c);
#endif
  if (n==20) { putchar('\n'); n=0; }
 }
 printf("\n};\n\n");
}

void fdump(char* fn, int n)
{
 FILE* f= (fn==NULL) ? stdin : fopen(fn,"rb");	/* must open in binary mode */
 if (f==NULL)
 {
  fprintf(stderr,"bin2c: cannot open ");
  perror(fn);
  exit(1);
 }
 else
 {
  if (fn!=NULL) printf("/* %s */\n",fn);
  dump(f,n);
  fclose(f);
 }
}

void emit(char* fn, int n)
{
 printf(" lua_dobuffer(B%d,sizeof(B%d),\"%s\");\n",n,n,fn);
}

int main(int argc, char* argv[])
{
 printf("/* code automatically generated by bin2c -- DO NOT EDIT */\n");
 printf("{\n");
 if (argc<2)
 {
  dump(stdin,0);
  emit("(stdin)",0);
 }
 else
 {
  int i;
  printf("/* #include'ing this file in a C program is equivalent to calling\n");
  for (i=1; i<argc; i++) printf("  lua_dofile(\"%s\");\n",argv[i]);
  printf("*/\n");
  for (i=1; i<argc; i++) fdump(argv[i],i);
  for (i=1; i<argc; i++) emit(argv[i],i);
 }
 printf("}\n");
 return 0;
}