/* This file is part of Lcrzo.
*/

int lcrzo_filename_truncate(const char *filename,
			lcrzo_int32 size)
{ int fd, ret;
  struct stat st1, st2;

  /*before removing, we verify if the file seems OK*/
  lcrzo_er(lcrzo_priv_filename_stat_get(filename, &st1));
  lcrzo_er(lcrzo_priv_stat_forbidslink(st1));
  lcrzo_er(lcrzo_priv_stat_forbidsnotreg(st1));

  /*open*/
  fd=LAURENT_open(filename, O_RDWR);
  if (fd==-1) return(LCRZO_ERR_FUOPEN);

  /*verify if the characteristics are the same*/
  lcrzo_efr(lcrzo_priv_fd_stat_get(fd, &st2), LAURENT_close(fd));
  lcrzo_efr(lcrzo_priv_stat_forbidschange(st1, st2), LAURENT_close(fd));

  /* truncate the file */
#if defined LCRZODEF_SYSTEM_Unix
  ret=ftruncate(fd, size);
  if (ret==-1) 
  { close(fd);
    return(LCRZO_ERR_FUFTRUNCATE);
  }
#elif defined LCRZODEF_SYSTEM_Windows
  ret=_chsize(fd, size);
  if (ret==-1)
  { _close(fd);
    return(LCRZO_ERR_FUCHSIZE);
  }
#else
 #error "Unknown value for LCRZODEF_SYSTEM"
#endif

  lcrzo_er(lcrzo_fd_close(fd));
  
  return(LCRZO_ERR_OK);
}

