aboutsummaryrefslogtreecommitdiff
path: root/src/librc/librc-misc.c
diff options
context:
space:
mode:
authorMike Frysinger <vapier@gentoo.org>2011-07-13 21:27:34 +0200
committerChristian Ruppert <idl0r@gentoo.org>2011-07-13 21:31:20 +0200
commitfdaf1c65cdcba2d9b83e02cc0d08fb6dbbd80a80 (patch)
tree6a106882bb41f58f7d6b06075569372d97c9774a /src/librc/librc-misc.c
parentef22868f3668fe833cdf297e619afe5b721f7716 (diff)
Add a new function, bool rc_getfile(const char *, char **, size_t *)
<snip> Read the entire @file into the buffer and set @len to the size of the buffer when finished. For C strings, this will be strlen(buffer) + 1. Don't forget to free the buffer afterwards! </snip> We also fix bug 374899 by adding this new function. X-Gentoo-Bug: 374899 X-Gentoo-Bug-URL: http://bugs.gentoo.org/374899
Diffstat (limited to 'src/librc/librc-misc.c')
-rw-r--r--src/librc/librc-misc.c48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/librc/librc-misc.c b/src/librc/librc-misc.c
index 7244deef..97fa54c8 100644
--- a/src/librc/librc-misc.c
+++ b/src/librc/librc-misc.c
@@ -54,6 +54,54 @@ rc_yesno(const char *value)
}
librc_hidden_def(rc_yesno)
+
+/**
+ * Read the entire @file into the buffer and set @len to the
+ * size of the buffer when finished. For C strings, this will
+ * be strlen(buffer) + 1.
+ * Don't forget to free the buffer afterwards!
+ */
+bool
+rc_getfile(const char *file, char **buffer, size_t *len)
+{
+ bool ret = false;
+ FILE *fp;
+ int fd;
+ struct stat st;
+ size_t done, left;
+
+ fp = fopen(file, "re");
+ if (!fp)
+ return false;
+
+ /* assume fileno() never fails */
+ fd = fileno(fp);
+
+ if (fstat(fd, &st))
+ goto finished;
+
+ left = st.st_size;
+ *len = left + 1; /* NUL terminator */
+ *buffer = xrealloc(*buffer, *len);
+ while (left) {
+ done = fread(*buffer, sizeof(*buffer[0]), left, fp);
+ if (done == 0 && ferror(fp))
+ goto finished;
+ left -= done;
+ }
+ ret = true;
+
+ finished:
+ if (!ret) {
+ free(*buffer);
+ *len = 0;
+ } else
+ (*buffer)[*len - 1] = '\0';
+ fclose(fp);
+ return ret;
+}
+librc_hidden_def(rc_getfile)
+
ssize_t
rc_getline(char **line, size_t *len, FILE *fp)
{