1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
/* $Id: readin.c 6394 2003-07-12 19:13:14Z rra $
**
*/
#include "config.h"
#include "clibrary.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "libinn.h"
/*
** Read a big amount, looping until it is all done. Return true if
** successful.
*/
int xread(int fd, char *p, off_t i)
{
int count;
for ( ; i; p += count, i -= count) {
do {
count = read(fd, p, i);
} while (count == -1 && errno == EINTR);
if (count <= 0)
return -1;
}
return 0;
}
/*
** Read an already-open file into memory.
*/
char *ReadInDescriptor(int fd, struct stat *Sbp)
{
struct stat mystat;
char *p;
int oerrno;
if (Sbp == NULL)
Sbp = &mystat;
/* Get the size, and enough memory. */
if (fstat(fd, Sbp) < 0) {
oerrno = errno;
close(fd);
errno = oerrno;
return NULL;
}
p = xmalloc(Sbp->st_size + 1);
/* Slurp, slurp. */
if (xread(fd, p, Sbp->st_size) < 0) {
oerrno = errno;
free(p);
close(fd);
errno = oerrno;
return NULL;
}
/* Terminate the string; terminate the routine. */
p[Sbp->st_size] = '\0';
return p;
}
/*
** Read a file into allocated memory. Optionally fill in the stat(2) data.
** Return a pointer to the file contents, or NULL on error.
*/
char *ReadInFile(const char *name, struct stat *Sbp)
{
char *p;
int fd;
if ((fd = open(name, O_RDONLY)) < 0)
return NULL;
p = ReadInDescriptor(fd, Sbp);
close(fd);
return p;
}
|