Statistics
| Branch: | Revision:

root / mainbox / util.c @ 5e03b78d

History | View | Annotate | Download (822 Bytes)

1
#include "util.h"
2
#include "log.h"
3
#include <stdlib.h>
4
#include <stdio.h>
5
#include <unistd.h>
6
#include <sys/types.h>
7
#include <sys/stat.h>
8
#include <fcntl.h>
9

    
10
char *read_file(const char *filename) {
11
  int fd, len, size, nread;
12
  char *str;
13
  
14
  fd = open(filename, O_RDONLY);
15
  if (fd < 0) {
16
    log_perror("open");
17
    return NULL;
18
  }
19

    
20
  len = 0;
21
  size = 64;
22
  str = malloc(size);
23
  if (!str) {
24
    close(fd);
25
    return NULL;
26
  }
27

    
28
  while (1) {
29
    nread = read(fd, str+len, size-len);
30
    len += nread;
31
    if (len == size) {
32
      size *= 2;
33
      str = realloc(str, size);
34
      if (!str)
35
        return NULL;
36
    }
37
    if (nread == 0) {
38
      str[len] = '\0';
39
      close(fd);
40
      return str;
41
    } else if (nread < 0) {
42
      log_perror("read");
43
      free(str);
44
      close(fd);
45
      return NULL;
46
    }
47
  }
48
}