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