aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorRob Landley <rob@landley.net>2020-02-10 19:47:02 -0600
committerRob Landley <rob@landley.net>2020-02-10 19:47:02 -0600
commit7d15b37b5c23c628929f161dc7df9121c6070cec (patch)
treefdf961b6f6b3c80832002ac69d6368fbf6180f5a /lib
parentdb188cde1f05ec42fd0c56bc9630788003708777 (diff)
downloadtoybox-7d15b37b5c23c628929f161dc7df9121c6070cec.tar.gz
Factor out readfd()
Diffstat (limited to 'lib')
-rw-r--r--lib/lib.c26
-rw-r--r--lib/lib.h1
2 files changed, 17 insertions, 10 deletions
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
+}
diff --git a/lib/lib.h b/lib/lib.h
index e2914a09..66b39d67 100644
--- a/lib/lib.h
+++ b/lib/lib.h
@@ -209,6 +209,7 @@ off_t lskip(int fd, off_t offset);
int mkpathat(int atfd, char *dir, mode_t lastmode, int flags);
int mkpath(char *dir);
struct string_list **splitpath(char *path, struct string_list **list);
+char *readfd(int fd, char *ibuf, off_t *plen);
char *readfileat(int dirfd, char *name, char *buf, off_t *len);
char *readfile(char *name, char *buf, off_t len);
void msleep(long milliseconds);