BSD 3 development
[unix-history] / usr / src / lib / libNS / filbuf.c
CommitLineData
1bd0b214
BJ
1/* Copyright (c) 1979 Regents of the University of California */
2#include <stdio.h>
3_filbuf(iop)
4register struct _iobuf *iop;
5{
6 static char smallbuf[_NFILE];
7 register n;
8 char *malloc();
9
10 if ((iop->_flag&_IOREAD) == 0)
11 _error("Reading bad file\n");
12 if (iop->_flag&_IOSTRG)
13 return(-1);
14tryagain:
15 if (iop->_base==NULL) {
16 if (iop->_flag&_IONBF) {
17 iop->_base = &smallbuf[fileno(iop)];
18 goto tryagain;
19 }
20 if ((iop->_base = malloc(BUFSIZ)) == NULL) {
21 iop->_flag |= _IONBF;
22 goto tryagain;
23 }
24 iop->_flag |= _IOMYBUF;
25 }
26 if((iop->_flag & _IODIRT) && !(iop->_flag & _IONBF) && (iop->_flag & _IOWRT)) {
27 if (iop->_delta)
28 if (lseek(iop->_file,(long) -iop->_delta, 1) < 0) {
29 _error("Seek error in filbuf\n");
30 iop->_flag |= _IOERR;
31 }
32 if( 0 < (n = iop->_ptr - iop->_base))
33 if( n != write(iop->_file, iop->_base, n) )
34 iop->_flag |= _IOERR;
35 iop->_flag &= ~_IODIRT;
36 }
37 iop->_ptr = iop->_base;
38 iop->_cnt = read(fileno(iop), iop->_ptr, iop->_flag&_IONBF?1:BUFSIZ);
39 iop->_delta = iop->_cnt;
40 if (--iop->_cnt < 0) {
41 if (iop->_cnt == -1)
42 iop->_flag |= _IOEOF;
43 else
44 iop->_flag |= _IOERR;
45 iop->_cnt = 0;
46 return(-1);
47 }
48 return(*iop->_ptr++&0377);
49}