rd_util.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. // Copyright (c) 1993-2011 PrBoom developers (see AUTHORS)
  2. // Licence: GPLv2 or later (see COPYING)
  3. // Useful utility functions
  4. #include "config.h"
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <stdarg.h>
  9. #include "rd_util.h"
  10. void ATTR((noreturn)) die(const char *error, ...)
  11. {
  12. va_list args;
  13. va_start(args, error);
  14. vfprintf(stderr, error, args);
  15. va_end(args);
  16. exit(1);
  17. }
  18. void *xmalloc(size_t size)
  19. {
  20. void *ptr = malloc(size);
  21. if (!ptr)
  22. die("Failure to allocate %lu bytes\n", (unsigned long)size);
  23. return ptr;
  24. }
  25. void *xrealloc(void *ptr, size_t size)
  26. {
  27. ptr = realloc(ptr, size);
  28. if (!ptr)
  29. die("Failure to reallocate %lu bytes\n", (unsigned long)size);
  30. return ptr;
  31. }
  32. void *xcalloc(size_t n, size_t size)
  33. {
  34. void *ptr = xmalloc(n * size);
  35. memset(ptr, 0, n * size);
  36. return ptr;
  37. }
  38. char *xstrdup(const char *s)
  39. {
  40. size_t size = strlen(s)+1;
  41. void *ptr = xmalloc(size);
  42. memcpy(ptr, s, size);
  43. return ptr;
  44. }
  45. static const char **search_paths = NULL;
  46. static size_t num_search_paths = 0;
  47. // slurp an entire file into memory or kill yourself
  48. size_t read_or_die(void **ptr, const char *file)
  49. {
  50. size_t size = 0, length = 0;
  51. void *buffer = NULL, *pos = buffer;
  52. FILE *f;
  53. f = fopen(file, "rb");
  54. if (!f)
  55. {
  56. int i;
  57. size_t s;
  58. char *path;
  59. for (i = 0; i < num_search_paths; i++)
  60. {
  61. s = strlen(search_paths[i]) + 1 + strlen(file) + 1;
  62. path = xmalloc(s);
  63. snprintf(path, s, "%s/%s", search_paths[i], file);
  64. f = fopen(path, "rb");
  65. free(path);
  66. }
  67. }
  68. if (!f)
  69. die("Cannot open %s\n", file);
  70. while (!feof(f))
  71. {
  72. size_t size_read;
  73. if (size >= length)
  74. {
  75. size += 4096;
  76. buffer = xrealloc(buffer, size);
  77. }
  78. pos = (char *)buffer + length; // don't assume sizeof(void)==1
  79. size_read = fread(pos, 1, 4096, f);
  80. length += size_read;
  81. }
  82. *ptr = buffer;
  83. return length;
  84. }
  85. void search_path(const char *path)
  86. {
  87. search_paths = xrealloc(search_paths,
  88. (++num_search_paths)*sizeof(*search_paths));
  89. search_paths[num_search_paths-1] = xstrdup(path);
  90. }