Revision ea46eeca
Simplified read_file
mainbox/util.c | ||
---|---|---|
2 | 2 |
#include "log.h" |
3 | 3 |
#include <stdlib.h> |
4 | 4 |
#include <stdio.h> |
5 |
#include <string.h> |
|
5 | 6 |
#include <errno.h> |
6 | 7 |
#include <unistd.h> |
7 | 8 |
#include <sys/types.h> |
8 | 9 |
#include <sys/stat.h> |
9 | 10 |
#include <fcntl.h> |
10 | 11 |
|
12 |
#define BUF_SIZE 1024 |
|
13 |
|
|
11 | 14 |
/* |
12 | 15 |
* read_file |
13 | 16 |
* |
14 |
* Reads in an entire file. Returns NULL on error, or a malloc'd pointer to a
|
|
15 |
* string which should later be freed. |
|
17 |
* Reads the first line of a file. Returns NULL on error, or a pointer to a
|
|
18 |
* malloc'd string which should later be freed.
|
|
16 | 19 |
*/ |
17 | 20 |
char *read_file(const char *filename) { |
18 |
int fd, len, size, nread; |
|
19 |
char *str; |
|
20 |
|
|
21 |
fd = open(filename, O_RDONLY); |
|
22 |
if (fd < 0) { |
|
21 |
char buf[BUF_SIZE]; |
|
22 |
int len; |
|
23 |
FILE *file; |
|
24 |
|
|
25 |
file = fopen(filename, "r"); |
|
26 |
if (file == NULL) { |
|
23 | 27 |
log_perror(filename); |
24 | 28 |
return NULL; |
25 | 29 |
} |
26 | 30 |
|
27 |
len = 0;
|
|
28 |
size = 64; |
|
29 |
str = malloc(size);
|
|
30 |
if (!str) {
|
|
31 |
close(fd);
|
|
31 |
fgets(buf, BUF_SIZE, file);
|
|
32 |
|
|
33 |
if (ferror(file)) {
|
|
34 |
log_perror(filename);
|
|
35 |
fclose(file);
|
|
32 | 36 |
return NULL; |
33 | 37 |
} |
34 | 38 |
|
35 |
while (1) { |
|
36 |
nread = read(fd, str+len, size-len); |
|
37 |
len += nread; |
|
38 |
if (len == size) { |
|
39 |
size *= 2; |
|
40 |
str = realloc(str, size); |
|
41 |
if (!str) |
|
42 |
return NULL; |
|
43 |
} |
|
44 |
if (nread == 0) { |
|
45 |
str[len] = '\0'; |
|
46 |
close(fd); |
|
47 |
return str; |
|
48 |
} else if (nread < 0) { |
|
49 |
log_perror("read"); |
|
50 |
free(str); |
|
51 |
close(fd); |
|
52 |
return NULL; |
|
53 |
} |
|
54 |
} |
|
39 |
len = strlen(buf); |
|
40 |
if (len > 0 && buf[len-1] == '\n') |
|
41 |
buf[len-1] = '\0'; |
|
42 |
|
|
43 |
fclose(file); |
|
44 |
return strdup(buf); |
|
55 | 45 |
} |
56 | 46 |
|
57 | 47 |
/* |
Also available in: Unified diff