simplify/refactor fflush and make fflush_unlocked an alias for fflush
[musl] / src / stdio / fflush.c
1 #include "stdio_impl.h"
2
3 /* stdout.c will override this if linked */
4 static FILE *volatile dummy = 0;
5 weak_alias(dummy, __stdout_used);
6
7 int fflush(FILE *f)
8 {
9         if (!f) {
10                 int r = __stdout_used ? fflush(__stdout_used) : 0;
11
12                 for (f=*__ofl_lock(); f; f=f->next)
13                         if (f->wpos > f->wbase) r |= fflush(f);
14                 __ofl_unlock();
15
16                 return r;
17         }
18
19         FLOCK(f);
20
21         /* If writing, flush output */
22         if (f->wpos > f->wbase) {
23                 f->write(f, 0, 0);
24                 if (!f->wpos) {
25                         FUNLOCK(f);
26                         return EOF;
27                 }
28         }
29
30         /* If reading, sync position, per POSIX */
31         if (f->rpos < f->rend) f->seek(f, f->rpos-f->rend, SEEK_CUR);
32
33         /* Clear read and write modes */
34         f->wpos = f->wbase = f->wend = 0;
35         f->rpos = f->rend = 0;
36
37         FUNLOCK(f);
38         return 0;
39 }
40
41 weak_alias(fflush, fflush_unlocked);