Ensure BUFFERSIZE is a power of 2
[openal-soft.git] / native-tools / bin2h.c
blob92f2b8a51f1537e884cd47bd5acd975bd33b1359
2 #ifdef _MSC_VER
3 #define _CRT_SECURE_NO_WARNINGS
4 #endif
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <errno.h>
11 int main (int argc, char *argv[])
13 char* input_name;
14 FILE* input_file;
16 char* output_name;
17 FILE* output_file;
19 char* variable_name;
21 if (4 != argc)
23 puts("Usage: bin2h [input] [output] [variable]");
24 return EXIT_FAILURE;
27 input_name = argv[1];
28 output_name = argv[2];
29 variable_name = argv[3];
31 input_file = fopen(input_name, "rb");
33 if (NULL == input_file)
35 printf("Could not open input file '%s': %s\n", input_name, strerror(errno));
36 return EXIT_FAILURE;
39 output_file = fopen(output_name, "w");
41 if (NULL == output_file)
43 printf("Could not open output file '%s': %s\n", output_name, strerror(errno));
44 return EXIT_FAILURE;
47 if (fprintf(output_file, "static const unsigned char %s[] = {", variable_name) < 0)
49 printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
50 return EXIT_FAILURE;
53 while (0 == feof(input_file))
55 unsigned char buffer[4096];
56 size_t i, count = fread(buffer, 1, sizeof(buffer), input_file);
58 if (sizeof(buffer) != count)
60 if (0 == feof(input_file) || 0 != ferror(input_file))
62 printf("Could not read from input file '%s': %s\n", input_name, strerror(ferror(input_file)));
63 return EXIT_FAILURE;
67 for (i = 0; i < count; ++i)
69 if ((i & 15) == 0)
71 if (fprintf(output_file, "\n ") < 0)
73 printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
74 return EXIT_FAILURE;
78 if (fprintf(output_file, "0x%2.2x, ", buffer[i]) < 0)
80 printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
81 return EXIT_FAILURE;
87 if (fprintf(output_file, "\n};\n") < 0)
89 printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
90 return EXIT_FAILURE;
93 if (fclose(output_file) < 0)
95 printf("Could not close output file '%s': %s\n", output_name, strerror(ferror(output_file)));
96 return EXIT_FAILURE;
99 return EXIT_SUCCESS;