/* fflush.c (emx+gcc) -- Copyright (c) 1990-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <sys/ioctl.h>

int fflush (FILE *stream)
{
  int result, n, ft;
  long pos;

  result = 0;
  if (stream == NULL)
    {
      for (n = 0; n < _nfiles; ++n)
        if ((_streamv[n].flags & (_IOOPEN|_IOWRT)) == (_IOOPEN|_IOWRT))
          if (fflush (&_streamv[n]) != 0)
            result = EOF;
      return (result);
    }
  if (stream->flags & _IOSPECIAL)
    {
      if (stream->flush != NULL)
        result = stream->flush (stream, _FLUSH_FLUSH);
      stream->flags &= ~_IOREREAD;    /* Undo ungetc */
      return (result);
    }
  if ((stream->flags & _IOWRT) && bbuf (stream))
    {
      n = stream->ptr - stream->buffer;
      if (n > 0 && write (fileno (stream), stream->buffer, n) <= 0)
        {
          stream->flags |= _IOERR;
          result = EOF;
        }
    }
  if ((stream->flags & _IOREAD) && bbuf (stream) &&
      ioctl (fileno (stream), FGETHTYPE, &ft) >= 0 && ft == HT_FILE)
    {
      pos = ftell (stream);
      if (pos == -1L)
        result = EOF;
      else if (lseek (fileno (stream), pos, SEEK_SET) == -1L)
        result = EOF;
    }
  stream->ptr = stream->buffer;
  stream->rcount = 0;
  stream->wcount = 0;
  stream->flags &= ~_IOREREAD;    /* Undo ungetc */
  return (result);
}
