logo

oasis

Own branch of Oasis Linux (upstream: <https://git.sr.ht/~mcf/oasis/>) git clone https://anongit.hacktivis.me/git/oasis.git

bin2c.c (1097B)


  1. #include <err.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <sys/stat.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. void
  8. usage(void)
  9. {
  10. errx(2, "usage: bin2c tablename [align]");
  11. }
  12. int
  13. main(int argc, char *argv[])
  14. {
  15. char buf[4096], *s, *table_name;
  16. ssize_t n;
  17. size_t total = 0, pad, align = 0;
  18. struct stat st;
  19. switch (argc) {
  20. case 3:
  21. align = strtoul(argv[2], &s, 10);
  22. if (*s)
  23. usage();
  24. case 2:
  25. table_name = argv[1];
  26. break;
  27. default:
  28. usage();
  29. }
  30. if (fstat(0, &st) < 0)
  31. err(1, "fstat 0");
  32. printf("unsigned char %s[] = {", table_name);
  33. for (;;) {
  34. n = read(0, buf, sizeof(buf));
  35. if (n < 0)
  36. err(1, "read");
  37. if (n == 0)
  38. break;
  39. for (s = buf; s < buf + n; ++s) {
  40. if (total++ % 8 == 0)
  41. printf("\n\t");
  42. printf("0x%02hhx,", *s);
  43. }
  44. }
  45. if (align) {
  46. for (pad = (total + (align - 1)) / align * align - total; pad; --pad) {
  47. if (total++ % 8 == 0)
  48. printf("\n\t");
  49. printf("0x00,");
  50. }
  51. }
  52. printf("\n};\n\nconst unsigned int %s_len = %zu;\n", table_name, total);
  53. printf("\nconst int %s_mtime = %ld;\n", table_name, st.st_mtime);
  54. return 0;
  55. }