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 */
35 int fd; /* file descriptor */
36 char *endp; /* one past the end */
37 char *ptr; /* current read pos */
38 int flags; /* file state */
39 char buf[BUFSIZ]; /* buffer */
42 FBFILE* fbopen(const char *filename, const char *mode)
57 openmode = O_WRONLY | O_CREAT | O_TRUNC;
58 pmode = S_IREAD | S_IWRITE;
61 openmode = O_WRONLY | O_CREAT | O_APPEND;
62 pmode = S_IREAD | S_IWRITE;
65 openmode &= ~(O_RDONLY | O_WRONLY);
74 * stop NFS hangs...most systems should be able to open a file in
75 * 3 seconds. -avalon (curtesy of wumpus)
78 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 *) MyMalloc(sizeof(FBFILE));
97 fb->ptr = fb->endp = fb->buf;
104 void fbclose(FBFILE* fb)
111 static int fbfill(FBFILE * fb)
117 n = read(fb->fd, fb->buf, BUFSIZ);
121 fb->endp = fb->buf + n;
124 fb->flags |= FB_FAIL;
130 int fbgetc(FBFILE * fb)
133 if (fb->ptr < fb->endp || fbfill(fb) > 0)
138 char *fbgets(char *buf, size_t len, FBFILE * fb)
145 if (fb->ptr == fb->endp && fbfill(fb) < 1)
158 else if ('\r' == *p) {
159 if (fb->ptr < fb->endp || fbfill(fb) > 0) {
160 if ('\n' == *fb->ptr)
167 if (fb->ptr == fb->endp && fbfill(fb) < 1)
174 int fbputs(const char *str, FBFILE * fb)
180 if (0 == fb->flags) {
181 n = write(fb->fd, str, strlen(str));
183 fb->flags |= FB_FAIL;
188 int fbstat(struct stat *sb, FBFILE * fb)
192 return fstat(fb->fd, sb);