/* fassign.c (emx+gcc) -- Copyright (c) 1996 by Eberhard Mattes */

#include <stdio.h>
#include <errno.h>
#include <sys/builtin.h>        /* For <sys/fmutex.h> */
#include <sys/fmutex.h>         /* For <sys/rmutex.h> */
#include <sys/rmutex.h>
#include <emx/io.h>

FILE *_fassign (FILE *target, FILE *source)
{
  /* Prevent other threads from reusing TARGET's slot while TARGET is
     closed. */

  STREAMV_LOCK;

  if (!(source->_flags & _IOOPEN))
    {
      STREAMV_UNLOCK;
      errno = EINVAL;
      return NULL;
    }

  /* Do nothing if TARGET and SOURCE are the same stream. */

  if (source == target)
    {
      STREAMV_UNLOCK;
      return target;
    }

  /* Close TARGET, ignoring errors. */

  fclose (target);

  /* Assign the stream. */

  *target = *source;
  if (target->_more != NULL)
    target->_more->owner = target;
  source->_flags = 0;
  STREAMV_UNLOCK;
  return target;
}
