1 #include "get_file_lines.h"
2 #include <talloc/talloc.h>
3 #include <string/string.h>
4 #include <noerr/noerr.h>
12 static void *grab_fd(const void *ctx, int fd)
15 unsigned int max = 16384, size = 0;
18 buffer = talloc_array(ctx, char, max+1);
19 while ((ret = read(fd, buffer + size, max - size)) > 0) {
22 buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
33 /* This version adds one byte (for nul term) */
34 static void *grab_file(const void *ctx, const char *filename)
39 if (streq(filename, "-"))
40 fd = dup(STDIN_FILENO);
42 fd = open(filename, O_RDONLY, 0);
47 buffer = grab_fd(ctx, fd);
52 /* This is a dumb one which copies. We could mangle instead. */
53 static char **split(const void *ctx, const char *text, const char *delims,
57 unsigned int max = 64, num = 0;
59 lines = talloc_array(ctx, char *, max+1);
61 while (*text != '\0') {
62 unsigned int len = strcspn(text, delims);
63 lines[num] = talloc_array(lines, char, len + 1);
64 memcpy(lines[num], text, len);
65 lines[num][len] = '\0';
67 text += strspn(text, delims);
69 lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
77 char **get_file_lines(void *ctx, const char *name, unsigned int *num_lines)
79 char *buffer = grab_file(ctx, name);
82 err(1, "Getting file %s", name);
84 return split(buffer, buffer, "\n", num_lines);