[ROSAPPS][HOST-TOOLS]:
[reactos.git] / reactos / tools / bin2c.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS bin2c
4 * FILE: tools/bin2c/bin2c.c
5 * PURPOSE: Converts a binary file into a byte array
6 * PROGRAMMER: Hermès Bélusca - Maïto
7 */
8
9 #include <stdio.h>
10
11 int main(int argc, char *argv[])
12 {
13 FILE* inFile;
14 FILE* outCFile;
15 FILE* outHFile;
16 unsigned char ch;
17 unsigned char cnt;
18
19 /* Validate the arguments */
20 if (argc < 5)
21 {
22 printf("Usage: bin2c infile.bin outfile.c outfile.h array_name [array_attribute [header_for_attribute]]\n");
23 return -1;
24 }
25
26 /* Open the input and output files */
27 inFile = fopen(argv[1], "rb");
28 if (!inFile)
29 {
30 printf("ERROR: Couldn't open data file '%s'.\n", argv[1]);
31 return -1;
32 }
33 outCFile = fopen(argv[2], "w");
34 if (!outCFile)
35 {
36 fclose(inFile);
37 printf("ERROR: Couldn't create output source file '%s'.\n", argv[2]);
38 return -1;
39 }
40 outHFile = fopen(argv[3], "w");
41 if (!outHFile)
42 {
43 fclose(outCFile);
44 fclose(inFile);
45 printf("ERROR: Couldn't create output header file '%s'.\n", argv[3]);
46 return -1;
47 }
48
49 /* Generate the header file and close it */
50 fprintf(outHFile, "/* This file is autogenerated, do not edit. */\n\n");
51 fprintf(outHFile, "#ifndef CHAR\n"
52 "#define CHAR char\n"
53 "#endif\n\n");
54 fprintf(outHFile, "extern CHAR %s[];\n", argv[4]);
55 fclose(outHFile);
56
57 /* Generate the source file and close it */
58 fprintf(outCFile, "/* This file is autogenerated, do not edit. */\n\n");
59 if (argc >= 7)
60 {
61 /* Include needed header for defining the array attribute */
62 fprintf(outCFile, "#include \"%s\"\n", argv[6]);
63 }
64 fprintf(outCFile, "#include \"%s\"\n\n", argv[3]);
65
66 /* Generate the data array */
67 if (argc >= 6)
68 {
69 /* Add the array attribute */
70 fprintf(outCFile, "%s ", argv[5]);
71 }
72 fprintf(outCFile, "CHAR %s[] =\n{", argv[4]);
73
74 cnt = 0;
75 ch = fgetc(inFile);
76 while (!feof(inFile))
77 {
78 if ((cnt % 16) == 0)
79 {
80 fprintf(outCFile, "\n ");
81 cnt = 0;
82 }
83 fprintf(outCFile, " 0x%02x,", (unsigned int)ch);
84 ++cnt;
85 ch = fgetc(inFile);
86 }
87 /* Put a final NULL terminator */
88 fprintf(outCFile, "\n 0x00");
89 fprintf(outCFile, "\n};\n");
90 fclose(outCFile);
91
92 /* Close the input file */
93 fclose(inFile);
94
95 return 0;
96 }
97
98 /* EOF */