/* chsize.c (emx+gcc) -- Copyright (c) 1992-1993 by Eberhard Mattes */

#include <sys/emx.h>
#include <strings.h>
#include <io.h>
#include <errno.h>

int chsize (int handle, long length)
{
  long n;
  int i, j;
  char zeros[4096];

  if (handle < 0 || handle >= _nfiles || (_files[handle] & F_DEV))
    {
      errno = EBADF;
      return (-1);
    }
  n = (long)__lseek (handle, 0L, SEEK_END);
  if (n == -1L)
    return (-1);
  if (__chsize (handle, length) != 0)
    return (-1);
  if (n < length)
    {
      bzero (zeros, sizeof (zeros));
      if (__lseek (handle, n, SEEK_SET) == -1)
        return (-1);
      while (n < length)
        {
          i = length - n;
          if (i > sizeof (zeros))
            i = sizeof (zeros);
          j = __write (handle, zeros, i);
          if (j == -1)
            return (-1);
          if (j == 0)
            {
              errno = ENOSPC;
              return (-1);
            }
          n += j;
        }
    }
  return (0);
}
