4
* Read the entire contents of a file into malloc'd storage. This
5
* is mostly useful for things like /proc files where we can't just
6
* fstat() to get the length and then mmap().
8
* Returns the number of bytes read, or -1 on error.
16
ssize_t freadfile(FILE *f, char **pp)
18
size_t bs; /* Decent starting point... */
19
size_t bf; /* Bytes free */
20
size_t bu = 0; /* Bytes used */
23
int old_errno = errno;
27
if ( !fstat(fileno(f), &st) && S_ISREG(st.st_mode) && st.st_size )
31
bs = BUFSIZ; /* A guess as good as any */
42
while ( bf && (rv = _fread(buffer+bu, bf, f)) ) {
47
if ( errno && errno != EINTR && errno != EAGAIN ) {
54
/* Hit EOF, no error */
56
/* Try to free superfluous memory */
57
if ( (nb = realloc(buffer, bu+1)) )
60
/* Null-terminate result for good measure */
68
/* Double the size of the buffer */
71
if ( !(nb = realloc(buffer, bs)) ) {
72
/* out of memory error */
80
ssize_t readfile(const char *filename, char **pp)
82
FILE *f = fopen(filename, "r");
88
rv = freadfile(f, pp);