xref: /plan9/sys/src/libstdio/fflush.c (revision 7dd7cddf99dd7472612f1413b4da293630e6b1bc)
1 /*
2  * pANS stdio -- fflush
3  */
4 #include "iolib.h"
5 /*
6  * pANS stdio -- data (put here, since loader won't load a separate file)
7  */
8 FILE _IO_stream[]={
9 /*	fd	flags	state	buf	rp	wp	lp	bufl	unbuf */
10 	0,	0,	OPEN,	0,	0,	0,	0,	0,	0,
11 	1,	0,	OPEN,	0,	0,	0,	0,	0,	0,
12 	2,	0,	OPEN,	0,	0,	0,	0,	0,	0,
13 };
14 
_fflush(FILE * f)15 int _fflush(FILE *f){
16 	int error, cnt;
17 
18 	if(f==NULL){
19 		error=0;
20 		for(f=_IO_stream;f!=&_IO_stream[FOPEN_MAX];f++)
21 			if(f->state==WR && _fflush(f)==EOF)
22 				error=EOF;
23 		return error;
24 	}
25 	if(f->flags&STRING) return EOF;
26 	switch(f->state){
27 	default:	/* OPEN RDWR EOF RD */
28 		return 0;
29 	case CLOSED:
30 	case ERR:
31 		return EOF;
32 	case WR:
33 		cnt=(f->flags&LINEBUF?f->lp:f->wp)-f->buf;
34 		if(cnt && write(f->fd, f->buf, cnt)!=cnt){
35 			f->state=ERR;
36 			return EOF;
37 		}
38 		f->rp=f->wp=f->buf;
39 		f->state=RDWR;
40 		return 0;
41 	}
42 }
43 
fflush(FILE * f)44 int fflush(FILE *f)
45 {
46 	int r;
47 
48 	qlock(&_stdiolk);
49 	r = _fflush(f);
50 	qunlock(&_stdiolk);
51 	return r;
52 }
53