xref: /plan9-contrib/sys/src/libstdio/fflush.c (revision 219b2ee8daee37f4aad58d63f21287faa8e4ffdc)
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 int fflush(FILE *f){
15 	int error, cnt;
16 	if(f==NULL){
17 		error=0;
18 		for(f=_IO_stream;f!=&_IO_stream[FOPEN_MAX];f++)
19 			if(f->state==WR && fflush(f)==EOF)
20 				error=EOF;
21 		return error;
22 	}
23 	if(f->flags&STRING) return EOF;
24 	switch(f->state){
25 	default:	/* OPEN RDWR EOF RD */
26 		return 0;
27 	case CLOSED:
28 	case ERR:
29 		return EOF;
30 	case WR:
31 		cnt=(f->flags&LINEBUF?f->lp:f->wp)-f->buf;
32 		if(cnt && write(f->fd, f->buf, cnt)!=cnt){
33 			f->state=ERR;
34 			return EOF;
35 		}
36 		f->rp=f->wp=f->buf;
37 		f->state=RDWR;
38 		return 0;
39 	}
40 }
41