1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 ssize_t safe_read(int fd, void *buf, size_t count)
17 n = read(fd, buf, count);
18 } while (n < 0 && errno == EINTR);
24 * Read all of the supplied buffer from a file.
25 * This does multiple reads as necessary.
26 * Returns the amount read, or -1 on an error.
27 * A short read is returned on an end of file.
29 ssize_t full_read(int fd, void *buf, size_t len)
37 cc = safe_read(fd, buf, len);
40 return cc; /* read() returns -1 on failure. */
43 buf = ((char *)buf) + cc;
51 // Die with an error message if we can't read the entire buffer.
52 void xread(int fd, void *buf, size_t count)
55 ssize_t size = full_read(fd, buf, count);
57 bb_error_msg_and_die("short read");
61 // Die with an error message if we can't read one character.
62 unsigned char xread_char(int fd)
69 // Read one line a-la fgets. Works only on seekable streams
70 char *reads(int fd, char *buffer, size_t size)
76 size = full_read(fd, buffer, size-1);
77 if ((ssize_t)size <= 0)
81 p = strchr(buffer, '\n');
85 // avoid incorrect (unsigned) widening
86 offset = (off_t)(p-buffer) - (off_t)size;
87 // set fd position right after '\n'
88 if (offset && lseek(fd, offset, SEEK_CUR) == (off_t)-1)
94 // Read one line a-la fgets. Reads byte-by-byte.
95 // Useful when it is important to not read ahead.
96 char *xmalloc_reads(int fd, char *buf)
99 int sz = buf ? strlen(buf) : 0;
105 buf = xrealloc(buf, sz + 128);
109 if (safe_read(fd, p, 1) != 1) { /* EOF/error */
111 /* we read nothing [and buf was NULL initially] */
122 return xrealloc(buf, p - buf);
125 ssize_t read_close(int fd, void *buf, size_t size)
128 size = full_read(fd, buf, size);
135 ssize_t open_read_close(const char *filename, void *buf, size_t size)
137 int fd = open(filename, O_RDONLY);
140 return read_close(fd, buf, size);
143 // Read (potentially big) files in one go. File size is estimated by
145 void *xmalloc_open_read_close(const char *filename, size_t *sizep)
148 size_t size = sizep ? *sizep : INT_MAX;
152 fd = xopen(filename, O_RDONLY);
153 /* /proc/N/stat files report len 0 here */
154 /* In order to make such files readable, we add small const */
155 len = xlseek(fd, 0, SEEK_END) | 0x3ff; /* + up to 1k */
156 xlseek(fd, 0, SEEK_SET);
159 buf = xmalloc(size + 1);
160 size = read_close(fd, buf, size);
161 if ((ssize_t)size < 0)
162 bb_perror_msg_and_die("'%s'", filename);
163 xrealloc(buf, size + 1);