]> git.ozlabs.org Git - ccan/blob - ccan/grab_file/grab_file.c
Initial TDB import.
[ccan] / ccan / grab_file / grab_file.c
1 #include "grab_file.h"
2 #include <ccan/talloc/talloc.h>
3 #include <ccan/noerr/noerr.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8
9 void *grab_fd(const void *ctx, int fd, size_t *size)
10 {
11         int ret;
12         size_t max = 16384, s;
13         char *buffer;
14
15         if (!size)
16                 size = &s;
17         *size = 0;
18
19         buffer = talloc_array(ctx, char, max+1);
20         while ((ret = read(fd, buffer + *size, max - *size)) > 0) {
21                 *size += ret;
22                 if (*size == max)
23                         buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
24         }
25         if (ret < 0) {
26                 talloc_free(buffer);
27                 buffer = NULL;
28         } else
29                 buffer[*size] = '\0';
30
31         return buffer;
32 }
33
34 void *grab_file(const void *ctx, const char *filename, size_t *size)
35 {
36         int fd;
37         char *buffer;
38
39         if (!filename)
40                 fd = dup(STDIN_FILENO);
41         else
42                 fd = open(filename, O_RDONLY, 0);
43
44         if (fd < 0)
45                 return NULL;
46
47         buffer = grab_fd(ctx, fd, size);
48         close_noerr(fd);
49         return buffer;
50 }