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.
24 #include "ircd_alloc.h" /* MyMalloc, MyFree */
26 #include <assert.h> /* assert */
27 #include <fcntl.h> /* O_RDONLY, O_WRONLY, ... */
28 #include <stdio.h> /* BUFSIZ, EOF */
29 #include <sys/stat.h> /* struct stat */
30 #include <unistd.h> /* read, write, open, close */
37 int fd; /* file descriptor */
38 char *endp; /* one past the end */
39 char *ptr; /* current read pos */
40 int flags; /* file state */
41 char buf[BUFSIZ]; /* buffer */
44 FBFILE* fbopen(const char *filename, const char *mode)
59 openmode = O_WRONLY | O_CREAT | O_TRUNC;
60 pmode = S_IREAD | S_IWRITE;
63 openmode = O_WRONLY | O_CREAT | O_APPEND;
64 pmode = S_IREAD | S_IWRITE;
67 openmode &= ~(O_RDONLY | O_WRONLY);
76 * stop NFS hangs...most systems should be able to open a file in
77 * 3 seconds. -avalon (curtesy of wumpus)
80 if ((fd = open(filename, openmode, pmode)) == -1) {
86 if (NULL == (fb = fdbopen(fd, NULL)))
91 FBFILE* fdbopen(int fd, const char *mode)
94 * ignore mode, if file descriptor hasn't been opened with the
95 * correct mode, the first use will fail
97 FBFILE *fb = (FBFILE *) MyMalloc(sizeof(FBFILE));
99 fb->ptr = fb->endp = fb->buf;
106 void fbclose(FBFILE* fb)
113 static int fbfill(FBFILE * fb)
119 n = read(fb->fd, fb->buf, BUFSIZ);
123 fb->endp = fb->buf + n;
126 fb->flags |= FB_FAIL;
132 int fbgetc(FBFILE * fb)
135 if (fb->ptr < fb->endp || fbfill(fb) > 0)
140 char *fbgets(char *buf, size_t len, FBFILE * fb)
147 if (fb->ptr == fb->endp && fbfill(fb) < 1)
160 else if ('\r' == *p) {
161 if (fb->ptr < fb->endp || fbfill(fb) > 0) {
162 if ('\n' == *fb->ptr)
169 if (fb->ptr == fb->endp && fbfill(fb) < 1)
176 int fbputs(const char *str, FBFILE * fb)
182 if (0 == fb->flags) {
183 n = write(fb->fd, str, strlen(str));
185 fb->flags |= FB_FAIL;
190 int fbstat(struct stat *sb, FBFILE * fb)
194 return fstat(fb->fd, sb);