Passo intermediario, ainda falta um longo caminho
[pspdecompiler.git] / utils.c
blob4d0c9ddee2f094020062ff3f664b42ff5a20fd5b
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <string.h>
5 #include <errno.h>
7 #include "utils.h"
9 void report (const char *fmt, ...)
11 va_list ap;
12 va_start (ap, fmt);
13 vfprintf (stdout, fmt, ap);
14 va_end (ap);
17 void error (const char *fmt, ...)
19 va_list ap;
20 va_start (ap, fmt);
21 vfprintf (stderr, fmt, ap);
22 fprintf (stderr, "\n");
23 va_end (ap);
26 void xerror (const char *fmt, ...)
28 va_list ap;
29 va_start (ap, fmt);
30 vfprintf (stderr, fmt, ap);
31 fprintf (stderr, ": %s\n", strerror (errno));
32 va_end (ap);
36 void fatal (const char *fmt, ...)
38 va_list ap;
39 va_start (ap, fmt);
40 fprintf (stderr, "fatal: ");
41 vfprintf (stderr, fmt, ap);
42 fprintf (stderr, "\n");
43 va_end (ap);
44 exit (1);
47 void xfatal (const char *fmt, ...)
49 va_list ap;
50 va_start (ap, fmt);
51 fprintf (stderr, "fatal: ");
52 vfprintf (stderr, fmt, ap);
53 fprintf (stderr, ": %s\n", strerror (errno));
54 va_end (ap);
55 exit (1);
58 void *xmalloc (size_t size)
60 void *ptr = malloc (size);
61 if (!ptr) fatal (__FILE__ ": memory exhausted");
62 return ptr;
65 void *xrealloc (void *ptr, size_t size)
67 void *nptr = realloc (ptr, size);
68 if (!nptr) fatal (__FILE__ ": can't realloc");
69 return nptr;
73 static
74 int _file_size (FILE *fp, const char *path, size_t *size)
76 long r;
78 if (fseek (fp, 0L, SEEK_END)) {
79 xerror (__FILE__ ": can't seek file `%s'", path);
80 fclose (fp);
81 return 0;
84 r = ftell (fp);
85 if (r == -1) {
86 xerror (__FILE__ ": can't get file size of `%s'", path);
87 return 0;
90 if (size) *size = (size_t) r;
91 return 1;
94 void *read_file (const char *path, size_t *size)
96 FILE *fp;
97 void *buffer;
98 size_t file_size;
99 size_t read_return;
101 fp = fopen (path, "rb");
102 if (!fp) {
103 xerror (__FILE__ ": can't open file `%s'", path);
104 return NULL;
107 if (!_file_size (fp, path, &file_size)) {
108 return NULL;
111 buffer = xmalloc (file_size);
112 rewind (fp);
114 read_return = fread (buffer, 1, file_size, fp);
115 fclose (fp);
117 if (read_return != file_size) {
118 error (__FILE__ ": can't fully read file `%s'", path);
119 free (buffer);
120 return NULL;
123 if (size) *size = file_size;
124 return buffer;