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

#include <string.h>
#include <io.h>
#include <errno.h>
#include <emx/io.h>
#include <emx/syscalls.h>

int _chsize (int handle, long length)
{
  long n;
  int i, j, *pflags;
  char zeros[4096];

  if ((pflags = _fd_flags (handle)) == NULL || (*pflags & 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)
    {
      memset (zeros, 0, 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;
}
