aboutsummaryrefslogtreecommitdiffstats
path: root/usr/klibc/stdio/fflush.c
blob: dfccd24d4f8d1c5ed46081e3a88e990a8c0fdb91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 * fflush.c
 */

#include "stdioint.h"

int __fflush(struct _IO_file_pvt *f)
{
	ssize_t rv;
	char *p;

	/*
	 * Flush any unused input data.  If there is input data, there
	 * won't be any output data.
	 */
	if (__unlikely(f->ibytes))
		return fseek(&f->pub, 0, SEEK_CUR);

	p = f->buf;
	while (f->obytes) {
		rv = write(f->pub._IO_fileno, p, f->obytes);
		if (rv == -1) {
			if (errno == EINTR || errno == EAGAIN)
				continue;
			f->pub._IO_error = true;
			return EOF;
		} else if (rv == 0) {
			/* EOF on output? */
			f->pub._IO_eof = true;
			return EOF;
		}

		p += rv;
		f->obytes -= rv;
	}

	return 0;
}

int fflush(FILE *file)
{
	struct _IO_file_pvt *f;

	if (__likely(file)) {
		f = stdio_pvt(file);
		return __fflush(f);
	} else {
		int err = 0;

		for (f = __stdio_headnode.next;
		     f != &__stdio_headnode;
		     f = f->next) {
			if (f->obytes)
				err |= __fflush(f);
		}
		return err;
	}
}