aboutsummaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/lib.c14
-rw-r--r--lib/lib.h6
2 files changed, 11 insertions, 9 deletions
diff --git a/lib/lib.c b/lib/lib.c
index b3703052..a16439e7 100644
--- a/lib/lib.c
+++ b/lib/lib.c
@@ -411,14 +411,16 @@ off_t fdlength(int fd)
}
// Read contents of file as a single nul-terminated string.
-// malloc new one if buf=len=0
-char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
+// measure file size if !len, allocate buffer if !buf
+// note: for existing buffers use len = size-1, will set buf[len] = 0
+char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
{
+ off_t len = *plen-!!ibuf;
int fd;
char *buf;
if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
- if (len<1) {
+ if (!len) {
len = fdlength(fd);
// proc files don't report a length, so try 1 page minimum.
if (len<4096) len = 4096;
@@ -426,11 +428,11 @@ char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
if (!ibuf) buf = xmalloc(len+1);
else buf = ibuf;
- len = readall(fd, buf, len-1);
+ *plen = len = readall(fd, buf, len);
close(fd);
if (len<0) {
if (ibuf != buf) free(buf);
- buf = 0;
+ buf = 0;
} else buf[len] = 0;
return buf;
@@ -438,7 +440,7 @@ char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
char *readfile(char *name, char *ibuf, off_t len)
{
- return readfileat(AT_FDCWD, name, ibuf, len);
+ return readfileat(AT_FDCWD, name, ibuf, &len);
}
// Sleep for this many thousandths of a second
diff --git a/lib/lib.h b/lib/lib.h
index 301c50f4..3047d379 100644
--- a/lib/lib.h
+++ b/lib/lib.h
@@ -154,7 +154,7 @@ ssize_t writeall(int fd, void *buf, size_t len);
off_t lskip(int fd, off_t offset);
int mkpathat(int atfd, char *dir, mode_t lastmode, int flags);
struct string_list **splitpath(char *path, struct string_list **list);
-char *readfileat(int dirfd, char *name, char *buf, off_t len);
+char *readfileat(int dirfd, char *name, char *buf, off_t *len);
char *readfile(char *name, char *buf, off_t len);
void msleep(long miliseconds);
int64_t peek_le(void *ptr, unsigned size);
@@ -256,14 +256,14 @@ void names_to_pid(char **names, int (*callback)(pid_t pid, char *name));
pid_t xvforkwrap(pid_t pid);
#define XVFORK() xvforkwrap(vfork())
-#define WOULD_EXIT(y, x) { jmp_buf _noexit; \
+#define WOULD_EXIT(y, x) do { jmp_buf _noexit; \
int _noexit_res; \
toys.rebound = &_noexit; \
_noexit_res = setjmp(_noexit); \
if (!_noexit_res) do {x;} while(0); \
toys.rebound = 0; \
y = _noexit_res; \
-}
+} while(0);
#define NOEXIT(x) WOULD_EXIT(_noexit_res, x)