Debian Codegraph @

prboom2/data/rd_util.c

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