]> git.ozlabs.org Git - ccan/blob - grab_file.h
96381875781e6db100876b3ee9a0ce8052b7a19d
[ccan] / grab_file.h
1 /* Licensed under LGPLv2+ - see LICENSE file for details */
2 #ifndef CCAN_GRAB_FILE_H
3 #define CCAN_GRAB_FILE_H
4 #include <stdio.h> // For size_t
5
6 /**
7  * grab_fd - read all of a file descriptor into memory
8  * @ctx: the context to tallocate from (often NULL)
9  * @fd: the file descriptor to read from
10  * @size: the (optional) size of the file
11  *
12  * This function reads from the given file descriptor until no more
13  * input is available.  The content is talloced off @ctx, and the size
14  * of the file places in @size if it's non-NULL.  For convenience, the
15  * byte after the end of the content will always be NUL.
16  *
17  * Example:
18  *      #include <ccan/str_talloc/str_talloc.h>
19  *      #include <ccan/talloc/talloc.h>
20  *      ...
21  *      // Return all of standard input, as lines.
22  *      static char **read_stdin_as_lines(void)
23  *      {
24  *              char **lines, *all;
25  *
26  *              all = grab_fd(NULL, 0, NULL);
27  *              if (!all)
28  *                      return NULL;
29  *              lines = strsplit(NULL, all, "\n");
30  *              talloc_free(all);
31  *              return lines;
32  *      }
33  */
34 void *grab_fd(const void *ctx, int fd, size_t *size);
35
36 /**
37  * grab_file - read all of a file (or stdin) into memory
38  * @ctx: the context to tallocate from (often NULL)
39  * @filename: the file to read (NULL for stdin)
40  * @size: the (optional) size of the file
41  *
42  * This function reads from the given file until no more input is
43  * available.  The content is talloced off @ctx, and the size of the
44  * file places in @size if it's non-NULL.  For convenience, the byte
45  * after the end of the content will always be NUL.
46  *
47  * Example:
48  *      // Return all of a given file, as lines.
49  *      static char **read_file_as_lines(const char *filename)
50  *      {
51  *              char **lines, *all;
52  *
53  *              all = grab_file(NULL, filename, NULL);
54  *              if (!all)
55  *                      return NULL;
56  *              lines = strsplit(NULL, all, "\n");
57  *              talloc_free(all);
58  *              return lines;
59  *      }
60  */
61 void *grab_file(const void *ctx, const char *filename, size_t *size);
62 #endif /* CCAN_GRAB_FILE_H */