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 "ircd_alloc.h" /* MyMalloc, MyFree */
24 #include <assert.h> /* assert */
25 #include <fcntl.h> /* O_RDONLY, O_WRONLY, ... */
26 #include <stdio.h> /* BUFSIZ, EOF */
27 #include <sys/stat.h> /* struct stat */
28 #include <unistd.h> /* read, write, open, close */
34 int fd; /* file descriptor */
35 char *endp; /* one past the end */
36 char *ptr; /* current read pos */
37 int flags; /* file state */
38 char buf[BUFSIZ]; /* buffer */
41 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) {
83 if (NULL == (fb = fdbopen(fd, NULL)))
88 FBFILE* fdbopen(int fd, const char *mode)
91 * ignore mode, if file descriptor hasn't been opened with the
92 * correct mode, the first use will fail
94 FBFILE *fb = (FBFILE *) MyMalloc(sizeof(FBFILE));
96 fb->ptr = fb->endp = fb->buf;
103 void fbclose(FBFILE* fb)
110 static int fbfill(FBFILE * fb)
116 n = read(fb->fd, fb->buf, BUFSIZ);
120 fb->endp = fb->buf + n;
123 fb->flags |= FB_FAIL;
129 int fbgetc(FBFILE * fb)
132 if (fb->ptr < fb->endp || fbfill(fb) > 0)
137 char *fbgets(char *buf, size_t len, FBFILE * fb)
144 if (fb->ptr == fb->endp && fbfill(fb) < 1)
157 else if ('\r' == *p) {
158 if (fb->ptr < fb->endp || fbfill(fb) > 0) {
159 if ('\n' == *fb->ptr)
166 if (fb->ptr == fb->endp && fbfill(fb) < 1)
173 int fbputs(const char *str, FBFILE * fb)
179 if (0 == fb->flags) {
180 n = write(fb->fd, str, strlen(str));
182 fb->flags |= FB_FAIL;
187 int fbstat(struct stat *sb, FBFILE * fb)
191 return fstat(fb->fd, sb);