1*46111Sbostic /*- 2*46111Sbostic * Copyright (c) 1990 The Regents of the University of California. 3*46111Sbostic * All rights reserved. 4*46111Sbostic * 5*46111Sbostic * This code is derived from software contributed to Berkeley by 6*46111Sbostic * Chris Torek. 7*46111Sbostic * 8*46111Sbostic * %sccs.include.redist.c% 9*46111Sbostic */ 10*46111Sbostic 11*46111Sbostic #if defined(LIBC_SCCS) && !defined(lint) 12*46111Sbostic static char sccsid[] = "@(#)fflush.c 5.1 (Berkeley) 01/20/91"; 13*46111Sbostic #endif /* LIBC_SCCS and not lint */ 14*46111Sbostic 15*46111Sbostic #include <sys/errno.h> 16*46111Sbostic #include <stdio.h> 17*46111Sbostic #include "local.h" 18*46111Sbostic 19*46111Sbostic /* Flush a single file, or (if fp is NULL) all files. */ 20*46111Sbostic fflush(fp) 21*46111Sbostic register FILE *fp; 22*46111Sbostic { 23*46111Sbostic if (fp == NULL) 24*46111Sbostic return (_fwalk(__sflush)); 25*46111Sbostic 26*46111Sbostic if ((fp->_flags & __SWR) == 0) { 27*46111Sbostic errno = EBADF; 28*46111Sbostic return (EOF); 29*46111Sbostic } 30*46111Sbostic return (__sflush(fp)); 31*46111Sbostic } 32*46111Sbostic 33*46111Sbostic __sflush(fp) 34*46111Sbostic register FILE *fp; 35*46111Sbostic { 36*46111Sbostic register unsigned char *p; 37*46111Sbostic register int n, t; 38*46111Sbostic 39*46111Sbostic t = fp->_flags; 40*46111Sbostic if ((t & __SWR) == 0) 41*46111Sbostic return (0); 42*46111Sbostic 43*46111Sbostic if ((p = fp->_bf._base) == NULL) 44*46111Sbostic return (0); 45*46111Sbostic 46*46111Sbostic n = fp->_p - p; /* write this much */ 47*46111Sbostic 48*46111Sbostic /* 49*46111Sbostic * Set these immediately to avoid problems with longjmp and to allow 50*46111Sbostic * exchange buffering (via setvbuf) in user write function. 51*46111Sbostic */ 52*46111Sbostic fp->_p = p; 53*46111Sbostic fp->_w = t & (__SLBF|__SNBF) ? 0 : fp->_bf._size; 54*46111Sbostic 55*46111Sbostic for (; n > 0; n -= t, p += t) { 56*46111Sbostic t = (*fp->_write)(fp->_cookie, (char *)p, n); 57*46111Sbostic if (t <= 0) { 58*46111Sbostic fp->_flags |= __SERR; 59*46111Sbostic return (EOF); 60*46111Sbostic } 61*46111Sbostic } 62*46111Sbostic return (0); 63*46111Sbostic } 64