root / mainbox / util.c @ 5305e5e7
History | View | Annotate | Download (797 Bytes)
1 | 15928a3d | Tom Mullins | #include "util.h" |
---|---|---|---|
2 | #include <stdlib.h> |
||
3 | #include <stdio.h> |
||
4 | #include <unistd.h> |
||
5 | #include <sys/types.h> |
||
6 | #include <sys/stat.h> |
||
7 | #include <fcntl.h> |
||
8 | |||
9 | char *read_file(const char *filename) { |
||
10 | int fd, len, size, nread;
|
||
11 | char *str;
|
||
12 | |||
13 | fd = open(filename, O_RDONLY); |
||
14 | if (fd < 0) { |
||
15 | perror("open");
|
||
16 | return NULL; |
||
17 | } |
||
18 | |||
19 | len = 0;
|
||
20 | size = 64;
|
||
21 | str = malloc(size); |
||
22 | if (!str) {
|
||
23 | close(fd); |
||
24 | return NULL; |
||
25 | } |
||
26 | |||
27 | while (1) { |
||
28 | nread = read(fd, str+len, size-len); |
||
29 | len += nread; |
||
30 | if (len == size) {
|
||
31 | size *= 2;
|
||
32 | str = realloc(str, size); |
||
33 | if (!str)
|
||
34 | return NULL; |
||
35 | } |
||
36 | if (nread == 0) { |
||
37 | str[len] = '\0';
|
||
38 | close(fd); |
||
39 | return str;
|
||
40 | } else if (nread < 0) { |
||
41 | perror("read");
|
||
42 | free(str); |
||
43 | close(fd); |
||
44 | return NULL; |
||
45 | } |
||
46 | } |
||
47 | } |