From 7d15b37b5c23c628929f161dc7df9121c6070cec Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Mon, 10 Feb 2020 19:47:02 -0600 Subject: Factor out readfd() --- lib/lib.c | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) (limited to 'lib/lib.c') diff --git a/lib/lib.c b/lib/lib.c index 4eef1355..b57a5691 100644 --- a/lib/lib.c +++ b/lib/lib.c @@ -508,21 +508,14 @@ off_t fdlength(int fd) return base; } -// Read contents of file as a single nul-terminated string. -// measure file size if !len, allocate buffer if !buf -// Existing buffers need len in *plen -// Returns amount of data read in *plen -char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen) +char *readfd(int fd, char *ibuf, off_t *plen) { off_t len, rlen; - int fd; char *buf, *rbuf; // Unsafe to probe for size with a supplied buffer, don't ever do that. if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat"); - if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0; - // If we dunno the length, probe it. If we can't probe, start with 1 page. if (!*plen) { if ((len = fdlength(fd))>0) *plen = len; @@ -543,7 +536,6 @@ char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen) len -= rlen; } *plen = len = rlen+(rbuf-buf); - close(fd); if (rlen<0) { if (ibuf != buf) free(buf); @@ -553,6 +545,20 @@ char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen) return buf; } +// Read contents of file as a single nul-terminated string. +// measure file size if !len, allocate buffer if !buf +// Existing buffers need len in *plen +// Returns amount of data read in *plen +char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen) +{ + if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0; + + ibuf = readfd(dirfd, ibuf, plen); + close(dirfd); + + return ibuf; +} + char *readfile(char *name, char *ibuf, off_t len) { return readfileat(AT_FDCWD, name, ibuf, &len); @@ -1434,4 +1440,4 @@ char *elf_arch_name(int type) } sprintf(libbuf, "unknown arch %d", type); return libbuf; -} \ No newline at end of file +} -- cgit v1.2.3