/* trunc.c (emx+gcc) */

#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <io.h>

#define FALSE 0
#define TRUE  1


static void usage (void)
{
  puts ("Usage: trunc [-c] <file> <size>");
  exit (1);
}


int main (int argc, char *argv[])
{
  char *p;
  int c, n, opt_c, handle;

  opt_c = FALSE;
  opterr = FALSE;
  while ((c = getopt (argc, argv, "c")) != EOF)
    switch (c)
      {
      case 'c':
        opt_c = TRUE;
        break;
      default:
        usage ();
      }
  if (argc - optind != 2)
    usage ();
  errno = 0;
  n = strtol (argv[optind+1], &p, 10);
  if (n < 0 || errno != 0 || *p != 0)
    usage ();
  if (opt_c)
    {
      handle = open (argv[optind], O_RDWR);
      if (handle == -1)
        {
          perror ("open");
          return (2);
        }
      else if (chsize (handle, n) != 0)
        {
          perror ("chsize");
          return (2);
        }
      else if (close (handle) != 0)
        {
          perror ("close");
          return (2);
        }
    }
  else
    {
      if (truncate (argv[optind], n) != 0)
        {
          perror ("truncate");
          return (2);
        }
    }
  return (0);
}
