Human68k CUI emulator with sound.
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.

tools.c 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <libgen.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <unistd.h>
  10. #include <dirent.h>
  11. #ifndef __EMSCRIPTEN__
  12. #include <zlib.h>
  13. #endif /* __EMSCRIPTEN */
  14. #include "tools.h"
  15. uint8_t *load_file(const char *filename, size_t *size_out) {
  16. FILE *f = fopen(filename, "rb");
  17. if(!f) {
  18. fprintf(
  19. stderr,
  20. "Could not open %s: %s (%d)\n",
  21. filename,
  22. strerror(errno),
  23. errno
  24. );
  25. return NULL;
  26. }
  27. fseek(f, 0, SEEK_END);
  28. size_t size = ftell(f);
  29. uint8_t *data = malloc(size);
  30. if(!data) {
  31. fprintf(
  32. stderr,
  33. "Could not allocate %lu bytes for %s: %s (%d)\n",
  34. size, filename, strerror(errno), errno
  35. );
  36. fclose(f);
  37. return NULL;
  38. }
  39. rewind(f);
  40. fread(data, 1, size, f);
  41. fclose(f);
  42. if(size_out) *size_out = size;
  43. return data;
  44. }
  45. int gcd(int a, int b) {
  46. int c = a % b;
  47. while(c > 0) {
  48. a = b;
  49. b = c;
  50. c = a % b;
  51. }
  52. return b;
  53. }
  54. void csv_quote(char *str, size_t len) {
  55. if(len == 0) len = strlen(str);
  56. if(str == 0) {
  57. putchar('\\');
  58. putchar('N');
  59. return;
  60. }
  61. putchar('"');
  62. for(int i = 0; i < len; i++) {
  63. switch(str[i]) {
  64. case 0:
  65. putchar('\\');
  66. putchar(0);
  67. break;
  68. case '\\':
  69. putchar('\\');
  70. putchar('\\');
  71. break;
  72. case '\b':
  73. putchar('\\');
  74. putchar('b');
  75. break;
  76. case '\n':
  77. putchar('\\');
  78. putchar('n');
  79. break;
  80. case '\r':
  81. putchar('\\');
  82. putchar('r');
  83. break;
  84. case '\t':
  85. putchar('\\');
  86. putchar('t');
  87. break;
  88. case 26:
  89. putchar('\\');
  90. putchar('Z');
  91. break;
  92. case '"':
  93. putchar('"');
  94. putchar('"');
  95. break;
  96. default: putchar(str[i]);
  97. }
  98. }
  99. putchar('"');
  100. }