Retirando os externs
[NesEmulator.git] / utils.c
blobcd52fbb60f7245ebcb85be9dedfa4ec624bdae1c
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 fprintf (stderr, "error: ");
22 vfprintf (stderr, fmt, ap);
23 fprintf (stderr, "\n");
24 va_end (ap);
27 void xerror (const char *fmt, ...)
29 va_list ap;
30 va_start (ap, fmt);
31 fprintf (stderr, "error: ");
32 vfprintf (stderr, fmt, ap);
33 fprintf (stderr, ": %s\n", strerror (errno));
34 va_end (ap);
38 void fatal (const char *fmt, ...)
40 va_list ap;
41 va_start (ap, fmt);
42 fprintf (stderr, "fatal: ");
43 vfprintf (stderr, fmt, ap);
44 fprintf (stderr, "\n");
45 va_end (ap);
46 exit (1);
49 void xfatal (const char *fmt, ...)
51 va_list ap;
52 va_start (ap, fmt);
53 fprintf (stderr, "fatal: ");
54 vfprintf (stderr, fmt, ap);
55 fprintf (stderr, ": %s\n", strerror (errno));
56 va_end (ap);
57 exit (1);
62 void *xmalloc (size_t size)
64 void *ptr = malloc (size);
65 if (!ptr) fatal ("memory exhausted");
66 return ptr;
69 void *read_file (const char *path, size_t *size)
71 FILE *fp;
72 void *buffer;
73 size_t file_size;
74 size_t read_return;
75 long r;
77 fp = fopen (path, "rb");
78 if (!fp) {
79 xerror ("can't open file `%s'", path);
80 return NULL;
83 if (fseek (fp, 0L, SEEK_END)) {
84 xerror ("can't seek file `%s'", path);
85 fclose (fp);
86 return NULL;
89 r = ftell (fp);
90 if (r == -1) {
91 xerror ("can't get file size of `%s'", path);
92 fclose (fp);
93 return NULL;
96 file_size = (size_t) r;
97 buffer = xmalloc (file_size);
98 rewind (fp);
100 read_return = fread (buffer, 1, file_size, fp);
101 fclose (fp);
103 if (read_return != file_size) {
104 error ("can't fully read file `%s'", path);
105 free (buffer);
106 return NULL;
109 if (size) *size = file_size;
110 return buffer;