/*
 * ftruncate.c - ftruncate()

    This file is part of libRILc, a standard C library for GCC on Amiga OS.
    Copyright © 1993, 1997, 1998  Rask Ingemann Lambertsen

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, if you link this library with files compiled
    with a GNU compiler to produce an executable, this does not cause the
    resulting executable to be covered by the GNU General Public License.
    This exception does not however invalidate any other reasons why the
    executable file might be covered by the GNU General Public License.


 * WARNING: Does not clear newly created bytes when extending a file.
 *
 * Could implement truncate() too.
 */

#include <dos/dos.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

#ifdef __PPC__
#include <ppcproto/dos.h>
#else
#include <proto/dos.h>
#endif

#include "internal/globals.h"
#include "internal/systemcalls.h"

int ftruncate (int fd, off_t size)
{
    ULONG newsize;
    __syscall_handle sh;

    /* Why do I just know that I have to programme defensively here?
     * I could use just d < 3 but anything in the zero page is invalid anyway. */
    if (fd >= -1 && fd < 4096)
    {
      errno = EBADF;
      __ioerr = ERROR_INVALID_LOCK;
      return (-1);
    }
    else
    {
      sh = __syscall_start ();
      newsize = SetFileSize (((FILE *) fd)->fh, (ULONG) size, OFFSET_BEGINNING);
      __syscall_end (sh);
    }

    if (newsize == (ULONG) -1 || newsize != (ULONG) size)
    {
        __seterrno ();
        return (-1);
    }
    else
        return (0);
}
