2 * IRC - Internet Relay Chat, ircd/fileio.c
3 * Copyright (C) 1998 Thomas Helvey <tomh@inxpress.net>
4 * Copyright (C) 1990 Jarkko Oikarinen and
5 * University of Oulu, Co Center
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 1, or (at your option)
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "runmalloc.h" /* RunMalloc, RunFree */
23 #include <stdio.h> /* BUFSIZ, EOF */
24 #include <fcntl.h> /* O_RDONLY, O_WRONLY, ... */
25 #include <unistd.h> /* read, write, open, close */
26 #include <assert.h> /* assert */
32 int fd; /* file descriptor */
33 char *endp; /* one past the end */
34 char *ptr; /* current read pos */
35 int flags; /* file state */
36 char buf[BUFSIZ]; /* buffer */
39 FBFILE *fbopen(const char *filename, const char *mode)
56 openmode = O_WRONLY | O_CREAT | O_TRUNC;
57 pmode = S_IREAD | S_IWRITE;
60 openmode = O_WRONLY | O_CREAT | O_APPEND;
61 pmode = S_IREAD | S_IWRITE;
64 openmode &= ~(O_RDONLY | O_WRONLY);
73 * stop NFS hangs...most systems should be able to open a file in
74 * 3 seconds. -avalon (curtesy of wumpus)
77 if ((fd = open(filename, openmode, pmode)) == -1)
84 if (NULL == (fb = fdbopen(fd, NULL)))
89 FBFILE *fdbopen(int fd, const char *mode)
92 * ignore mode, if file descriptor hasn't been opened with the
93 * correct mode, the first use will fail
95 FBFILE *fb = (FBFILE *) RunMalloc(sizeof(FBFILE));
98 fb->ptr = fb->endp = fb->buf;
105 void fbclose(FBFILE * fb)
112 static int fbfill(FBFILE * fb)
118 n = read(fb->fd, fb->buf, BUFSIZ);
122 fb->endp = fb->buf + n;
125 fb->flags |= FB_FAIL;
131 int fbgetc(FBFILE * fb)
134 if (fb->ptr < fb->endp || fbfill(fb) > 0)
139 char *fbgets(char *buf, size_t len, FBFILE * fb)
146 if (fb->ptr == fb->endp && fbfill(fb) < 1)
162 if (fb->ptr < fb->endp || fbfill(fb) > 0)
164 if ('\n' == *fb->ptr)
171 if (fb->ptr == fb->endp && fbfill(fb) < 1)
178 int fbputs(const char *str, FBFILE * fb)
186 n = write(fb->fd, str, strlen(str));
188 fb->flags |= FB_FAIL;
193 int fbstat(struct stat *sb, FBFILE * fb)
197 return fstat(fb->fd, sb);