|
|
1.1 root 1: /* @(#)flsbuf.c 4.2 (Berkeley) 3/9/81 */
2: #include <stdio.h>
3:
4: char *malloc();
5: int _setcleanup = 1;
6:
7: _flsbuf(c, iop)
8: register FILE *iop;
9: {
10: register unsigned char *base;
11: register n, rn;
12: char c1;
13: extern unsigned char _sobuf[];
14: extern _cleanup();
15:
16: if(_setcleanup){
17: _setcleanup = 0;
18: onexit(_cleanup);
19: }
20: c &= 0xFF; /* must be unsigned */
21: if (iop->_flag & _IORW) {
22: iop->_flag |= _IOWRT;
23: iop->_flag &= ~_IOEOF;
24: }
25:
26: if ((iop->_flag&_IOWRT)==0)
27: return(EOF);
28: tryagain:
29: if (iop->_flag&_IOLBF) {
30: base = iop->_base;
31: *iop->_ptr++ = c;
32: if (iop->_ptr >= base+BUFSIZ || c == '\n') {
33: n = write(fileno(iop), base, rn = iop->_ptr - base);
34: iop->_ptr = base;
35: } else
36: rn = n = 0;
37: iop->_cnt = 0;
38: } else if (iop->_flag&_IONBF) {
39: c1 = c;
40: rn = 1;
41: n = write(fileno(iop), &c1, rn);
42: iop->_cnt = 0;
43: } else {
44: if ((base=iop->_base)==NULL) {
45: if (iop==stdout) {
46: if (isatty(fileno(stdout)))
47: iop->_flag |= _IOLBF;
48: iop->_base = _sobuf;
49: iop->_ptr = _sobuf;
50: goto tryagain;
51: }
52: if ((iop->_base=base=(unsigned char *)malloc(BUFSIZ)) == NULL) {
53: iop->_flag |= _IONBF;
54: goto tryagain;
55: }
56: iop->_flag |= _IOMYBUF;
57: rn = n = 0;
58: } else if ((rn = n = iop->_ptr - base) > 0) {
59: iop->_ptr = base;
60: n = write(fileno(iop), base, n);
61: }
62: iop->_cnt = BUFSIZ-1;
63: *base++ = c;
64: iop->_ptr = base;
65: }
66: if (rn != n) {
67: iop->_flag |= _IOERR;
68: return(EOF);
69: }
70: return(c);
71: }
72:
73: fflush(iop)
74: register struct _iobuf *iop;
75: {
76: register unsigned char *base;
77: register n;
78:
79: if ((iop->_flag&(_IONBF|_IOWRT))==_IOWRT
80: && (base=iop->_base)!=NULL && (n=iop->_ptr-base)>0) {
81: iop->_ptr = base;
82: iop->_cnt = (iop->_flag&(_IOLBF|_IONBF)) ? 0 : BUFSIZ;
83: if (write(fileno(iop), base, n)!=n) {
84: iop->_flag |= _IOERR;
85: return(EOF);
86: }
87: }
88: return(0);
89: }
90:
91: /*
92: * Flush buffers on exit
93: */
94:
95: _cleanup()
96: {
97: register struct _iobuf *iop;
98: extern struct _iobuf *_lastbuf;
99:
100: for (iop = _iob; iop < _lastbuf; iop++)
101: fclose(iop);
102: }
103:
104: fclose(iop)
105: register struct _iobuf *iop;
106: {
107: register r;
108:
109: r = EOF;
110: if (iop->_flag&(_IOREAD|_IOWRT|_IORW) && (iop->_flag&_IOSTRG)==0) {
111: r = fflush(iop);
112: if (close(fileno(iop)) < 0)
113: r = EOF;
114: if (iop->_flag&_IOMYBUF)
115: free(iop->_base);
116: if (iop->_flag&(_IOMYBUF|_IONBF|_IOLBF))
117: iop->_base = NULL;
118: }
119: iop->_flag &= ~(_IOREAD|_IOWRT|_IOLBF|_IONBF|_IOMYBUF|_IOERR|_IOEOF|_IOSTRG|_IORW);
120: iop->_cnt = 0;
121: return(r);
122: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.