]> git.ozlabs.org Git - ccan/blob - ccan/tal/grab_file/grab_file.h
tal/grab_file: be robust against EINTR.
[ccan] / ccan / tal / grab_file / grab_file.h
1 /* Licensed under LGPLv2+ - see LICENSE file for details */
2 #ifndef CCAN_TAL_GRAB_FILE_H
3 #define CCAN_TAL_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  *
11  * This function reads from the given file descriptor until no more
12  * input is available.  The content is talloced off @ctx, and the
13  * tal_count() is the size in bytes plus one: for convenience, the
14  * byte after the end of the content will always be NUL.
15  *
16  * Note that this does *not* currently exit on EINTR, but continues
17  * reading.
18  *
19  * Example:
20  *      #include <ccan/tal/str/str.h>
21  *      #include <ccan/tal/tal.h>
22  *      ...
23  *      // Return all of standard input, as lines.
24  *      static char **read_stdin_as_lines(void)
25  *      {
26  *              char **lines, *all;
27  *
28  *              all = grab_fd(NULL, 0);
29  *              if (!all)
30  *                      return NULL;
31  *              lines = tal_strsplit(NULL, all, "\n", STR_EMPTY_OK);
32  *              tal_free(all);
33  *              return lines;
34  *      }
35  */
36 void *grab_fd(const void *ctx, int fd);
37
38 /**
39  * grab_file - read all of a file (or stdin) into memory
40  * @ctx: the context to tallocate from (often NULL)
41  * @filename: the file to read (NULL for stdin)
42  *
43  * This function reads from the given file until no more input is
44  * available.  The content is talloced off @ctx, and the tal_count()
45  * is the size in bytes plus one: for convenience, the byte after the
46  * end of the content will always be NUL.
47  *
48  * Example:
49  *      // Return all of a given file, as lines.
50  *      static char **read_file_as_lines(const char *filename)
51  *      {
52  *              char **lines, *all;
53  *
54  *              all = grab_file(NULL, filename);
55  *              if (!all)
56  *                      return NULL;
57  *              lines = tal_strsplit(NULL, all, "\n", STR_EMPTY_OK);
58  *              tal_free(all);
59  *              return lines;
60  *      }
61  */
62 void *grab_file(const void *ctx, const char *filename);
63 #endif /* CCAN_TAL_GRAB_FILE_H */