1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <sys/fcntl.h>
5 
6 #ifdef __DragonFly__
7 #include <errno.h>
8 #else
9 extern errno;
10 #endif
11 
loadfile(path)12 char *loadfile(path)
13 char *path;
14 {
15     /* Opens file path, reads contents into malloc'd buffer,
16      * appends null character to buffer, returns ptr to buffer.
17 
18      * Returns NULL if can't open/read file or can't malloc space.
19      * The cases can be distinguished by errno=0 for latter case.
20 
21      * Comment: the file is assumed to be a "normal file"; i.e.
22      * a single read will return all data in the file.
23      */
24 
25     struct stat statbuf;
26     char *data;
27     char *malloc();
28     int fd;
29 
30     if (stat(path, &statbuf) == -1)
31 	return NULL;
32 
33     data = malloc(statbuf.st_size+1);
34     if (data == NULL) {
35 	errno = 0;
36 	return NULL;
37     }
38     data[statbuf.st_size] = '\0';
39 
40     fd = open(path, O_RDONLY);
41     if (fd == -1) {
42 	(void) free(data);
43 	return NULL;
44     }
45 
46     if (read(fd, data, statbuf.st_size) != statbuf.st_size) {
47 	(void) free(data);
48 	return NULL;
49     }
50 
51     return data;
52 }
53