summaryrefslogtreecommitdiff
path: root/src/lua2c.c
blob: 4affa818bd5c56305eaad6710ae2f58229e6c0bb (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
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>

unsigned char *buffer;

int main(int argc, char *argv[])
{
    int fd_size;
    FILE *source, *dest;
    int i;

    if (argc != 3) {
        printf("bin2c\n" "Usage: lua2c infile outfile\n\n");
        return 1;
    }

    if ((source = fopen(argv[1], "rb")) == NULL) {
        printf("Error opening %s for reading.\n", argv[1]);
        return 1;
    }

    fseek(source, 0, SEEK_END);
    fd_size = ftell(source);
    fseek(source, 0, SEEK_SET);

    buffer = malloc(fd_size);
    if (buffer == NULL) {
        printf("Failed to allocate memory.\n");
        return 1;
    }

    if (fread(buffer, 1, fd_size, source) != fd_size) {
        printf("Failed to read file.\n");
        return 1;
    }
    fclose(source);

    if ((dest = fopen(argv[2], "w+")) == NULL) {
        printf("Failed to open/create %s.\n", argv[2]);
        return 1;
    }

    fprintf(dest, "{\n");
    fprintf(dest, "static const unsigned char B1[] = {");

    for (i = 0; i < fd_size; i += 1) {
        if ((i % 16) == 0)
            fprintf(dest, "\n\t");
        fprintf(dest, "0x%02x, ", buffer[i]);
    }

    fprintf(dest, "\n};\n\n if (luaL_loadbuffer(L, (const char *)B1, sizeof(B1), \"%s\") == 0) lua_call(L, 0, 0);\n}\n", argv[1]);

    fclose(dest);

    return 0;
}