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. */
45 buf = ((char *)buf) + cc;
53 // Die with an error message if we can't read the entire buffer.
54 void xread(int fd, void *buf, size_t count)
57 ssize_t size = full_read(fd, buf, count);
59 bb_error_msg_and_die("short read");
63 // Die with an error message if we can't read one character.
64 unsigned char xread_char(int fd)
73 // Read one line a-la fgets. Works only on seekable streams
74 char *reads(int fd, char *buffer, size_t size)
80 size = full_read(fd, buffer, size-1);
81 if ((ssize_t)size <= 0)
85 p = strchr(buffer, '\n');
89 offset = (p-buffer) - size;
90 // set fd position the right after the \n
91 if (offset && lseek(fd, offset, SEEK_CUR) == (off_t)-1)
97 ssize_t read_close(int fd, void *buf, size_t size)
100 size = full_read(fd, buf, size);
107 ssize_t open_read_close(const char *filename, void *buf, size_t size)
109 int fd = open(filename, O_RDONLY);
112 return read_close(fd, buf, size);
115 void *xmalloc_open_read_close(const char *filename, size_t *sizep)
118 size_t size = sizep ? *sizep : INT_MAX;
119 int fd = xopen(filename, O_RDONLY);
120 off_t len = xlseek(fd, 0, SEEK_END);
121 xlseek(fd, 0, SEEK_SET);
124 bb_error_msg_and_die("file '%s' is too big", filename);
126 buf = xmalloc(size+1);
127 size = read_close(fd, buf, size);
128 if ((ssize_t)size < 0)
129 bb_perror_msg_and_die("'%s'", filename);
131 if (sizep) *sizep = size;