Factor out readfd()

This commit is contained in:
Rob Landley 2020-02-10 19:47:02 -06:00
parent db188cde1f
commit 7d15b37b5c
2 changed files with 17 additions and 10 deletions

View File

@ -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;
}
}

View 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);