diff options
author | Rob Landley <rob@landley.net> | 2020-02-10 19:47:02 -0600 |
---|---|---|
committer | Rob Landley <rob@landley.net> | 2020-02-10 19:47:02 -0600 |
commit | 7d15b37b5c23c628929f161dc7df9121c6070cec (patch) | |
tree | fdf961b6f6b3c80832002ac69d6368fbf6180f5a /lib | |
parent | db188cde1f05ec42fd0c56bc9630788003708777 (diff) | |
download | toybox-7d15b37b5c23c628929f161dc7df9121c6070cec.tar.gz |
Factor out readfd()
Diffstat (limited to 'lib')
-rw-r--r-- | lib/lib.c | 26 | ||||
-rw-r--r-- | lib/lib.h | 1 |
2 files changed, 17 insertions, 10 deletions
@@ -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 +} @@ -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); |