ansi-to-src.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define ZF_LOGD(...)
  5. /**
  6. * Display a repr of the given string.
  7. *
  8. * This converts most \n\r\v\f\t codes,
  9. * defaults to \xHH (hex value).
  10. */
  11. char *repr(const char *data) {
  12. static char buffer[40960];
  13. char *cp;
  14. strcpy(buffer, data);
  15. cp = buffer;
  16. while (*cp != 0) {
  17. char c = *cp;
  18. if (isspace(c)) {
  19. if (c == ' ') {
  20. cp++;
  21. continue;
  22. };
  23. /* Ok, it's form-feed ('\f'), newline ('\n'), carriage return ('\r'),
  24. * horizontal tab ('\t'), and vertical tab ('\v') */
  25. memmove(cp + 1, cp, strlen(cp) + 1);
  26. *cp = '\\';
  27. cp++;
  28. switch (c) {
  29. case '\f':
  30. *cp = 'f';
  31. cp++;
  32. break;
  33. case '\n':
  34. *cp = 'n';
  35. cp++;
  36. break;
  37. case '\r':
  38. *cp = 'r';
  39. cp++;
  40. break;
  41. case '\t':
  42. *cp = 't';
  43. cp++;
  44. break;
  45. case '\v':
  46. *cp = 'v';
  47. cp++;
  48. break;
  49. default:
  50. *cp = '?';
  51. cp++;
  52. break;
  53. }
  54. continue;
  55. }
  56. if (isprint(c)) {
  57. cp++;
  58. continue;
  59. };
  60. // Ok, default to \xHH output.
  61. memmove(cp + 3, cp, strlen(cp) + 1);
  62. *cp = '\\';
  63. cp++;
  64. *cp = 'x';
  65. cp++;
  66. char buffer[3];
  67. sprintf(buffer, "%02x", (int)c & 0xff);
  68. *cp = buffer[0];
  69. cp++;
  70. *cp = buffer[1];
  71. cp++;
  72. continue;
  73. }
  74. return buffer;
  75. }
  76. int read_file(const char *filename) {
  77. FILE *fp;
  78. char buffer[10240];
  79. int read;
  80. fp = fopen(filename, "rb");
  81. if (fp == NULL) {
  82. ZF_LOGD("Failed to open %s", filename);
  83. return 0;
  84. }
  85. strcpy(buffer, filename);
  86. char *cp;
  87. if ((cp = strchr(buffer, '.')) != NULL) {
  88. *cp = 0;
  89. }
  90. cp = buffer;
  91. while (*cp != 0) {
  92. if (! isalpha(*cp))
  93. memmove(cp, cp+1, strlen(cp));
  94. cp++;
  95. }
  96. printf( "const char * %s[] = {\n", buffer);
  97. if ((read = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
  98. char *nl;
  99. buffer[read] = 0;
  100. cp = repr(buffer);
  101. int first = 1;
  102. while ((nl = strstr(cp, "\\r\\n")) != NULL) {
  103. strcpy(nl, "\"");
  104. if (!first) {
  105. printf(",\n");
  106. };
  107. first = 0;
  108. printf(" \"%s", cp);
  109. cp = nl + 4;
  110. }
  111. if (strlen(cp) > 0)
  112. printf( ",\n \"%s\"\n", cp);
  113. else
  114. printf("\n");
  115. printf("}\n");
  116. };
  117. fclose(fp);
  118. return 1;
  119. }
  120. int main(int argc, char *argv[]) {
  121. read_file(argv[1]);
  122. return 0;
  123. }