🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.5 KiB

  1. #ifdef _MSC_VER
  2. #define _CRT_SECURE_NO_WARNINGS
  3. #endif
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. int main (int argc, char *argv[])
  9. {
  10. char* input_name;
  11. FILE* input_file;
  12. char* output_name;
  13. FILE* output_file;
  14. char* variable_name;
  15. if (4 != argc)
  16. {
  17. puts("Usage: bin2h [input] [output] [variable]");
  18. return EXIT_FAILURE;
  19. }
  20. input_name = argv[1];
  21. output_name = argv[2];
  22. variable_name = argv[3];
  23. input_file = fopen(input_name, "rb");
  24. if (NULL == input_file)
  25. {
  26. printf("Could not open input file '%s': %s\n", input_name, strerror(errno));
  27. return EXIT_FAILURE;
  28. }
  29. output_file = fopen(output_name, "w");
  30. if (NULL == output_file)
  31. {
  32. printf("Could not open output file '%s': %s\n", output_name, strerror(errno));
  33. return EXIT_FAILURE;
  34. }
  35. if (fprintf(output_file, "static const unsigned char %s[] = {", variable_name) < 0)
  36. {
  37. printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
  38. return EXIT_FAILURE;
  39. }
  40. while (0 == feof(input_file))
  41. {
  42. unsigned char buffer[4096];
  43. size_t i, count = fread(buffer, 1, sizeof(buffer), input_file);
  44. if (sizeof(buffer) != count)
  45. {
  46. if (0 == feof(input_file) || 0 != ferror(input_file))
  47. {
  48. printf("Could not read from input file '%s': %s\n", input_name, strerror(ferror(input_file)));
  49. return EXIT_FAILURE;
  50. }
  51. }
  52. for (i = 0; i < count; ++i)
  53. {
  54. if ((i & 15) == 0)
  55. {
  56. if (fprintf(output_file, "\n ") < 0)
  57. {
  58. printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
  59. return EXIT_FAILURE;
  60. }
  61. }
  62. if (fprintf(output_file, "0x%2.2x, ", buffer[i]) < 0)
  63. {
  64. printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
  65. return EXIT_FAILURE;
  66. }
  67. }
  68. }
  69. if (fprintf(output_file, "\n};\n") < 0)
  70. {
  71. printf("Could not write to output file '%s': %s\n", output_name, strerror(ferror(output_file)));
  72. return EXIT_FAILURE;
  73. }
  74. if (fclose(output_file) < 0)
  75. {
  76. printf("Could not close output file '%s': %s\n", output_name, strerror(ferror(output_file)));
  77. return EXIT_FAILURE;
  78. }
  79. return EXIT_SUCCESS;
  80. }