coreutils/lib/ftruncate.c

91 lines
1.6 KiB
C
Raw Normal View History

1992-11-01 04:42:48 +08:00
/* ftruncate emulations that work on some System V's.
1994-08-19 21:13:48 +08:00
This file is in the public domain. */
2005-09-22 14:05:39 +08:00
#ifdef HAVE_CONFIG_H
1998-03-15 19:09:10 +08:00
# include <config.h>
1994-08-19 21:13:48 +08:00
#endif
1992-11-01 04:42:48 +08:00
#include <sys/types.h>
#include <fcntl.h>
#ifdef F_CHSIZE
1994-08-19 21:13:48 +08:00
1992-11-01 04:42:48 +08:00
int
1998-12-07 11:12:10 +08:00
ftruncate (int fd, off_t length)
1992-11-01 04:42:48 +08:00
{
return fcntl (fd, F_CHSIZE, length);
}
1994-08-19 21:13:48 +08:00
#else /* not F_CHSIZE */
1998-03-15 19:09:10 +08:00
# ifdef F_FREESP
1994-08-19 21:13:48 +08:00
/* By William Kucharski <kucharsk@netcom.com>. */
1992-11-01 04:42:48 +08:00
1998-03-15 19:09:10 +08:00
# include <sys/stat.h>
# include <errno.h>
# include <unistd.h>
1992-11-01 04:42:48 +08:00
int
1998-12-07 11:12:10 +08:00
ftruncate (int fd, off_t length)
1992-11-01 04:42:48 +08:00
{
struct flock fl;
struct stat filebuf;
if (fstat (fd, &filebuf) < 0)
return -1;
if (filebuf.st_size < length)
{
/* Extend file length. */
if (lseek (fd, (length - 1), SEEK_SET) < 0)
return -1;
/* Write a "0" byte. */
if (write (fd, "", 1) != 1)
return -1;
}
else
{
1994-08-19 21:13:48 +08:00
1992-11-01 04:42:48 +08:00
/* Truncate length. */
1994-08-19 21:13:48 +08:00
1992-11-01 04:42:48 +08:00
fl.l_whence = 0;
fl.l_len = 0;
fl.l_start = length;
1994-08-19 21:13:48 +08:00
fl.l_type = F_WRLCK; /* write lock on file space */
/* This relies on the *undocumented* F_FREESP argument to fcntl,
which truncates the file so that it ends at the position
indicated by fl.l_start. Will minor miracles never cease? */
1992-11-01 04:42:48 +08:00
if (fcntl (fd, F_FREESP, &fl) < 0)
return -1;
}
return 0;
}
1994-08-19 21:13:48 +08:00
1998-03-15 19:09:10 +08:00
# else /* not F_CHSIZE nor F_FREESP */
# if HAVE_CHSIZE
1994-08-19 21:13:48 +08:00
1992-11-01 04:42:48 +08:00
int
1998-12-07 11:12:10 +08:00
ftruncate (int fd, off_t length)
1992-11-01 04:42:48 +08:00
{
return chsize (fd, length);
}
1994-08-19 21:13:48 +08:00
1998-03-15 19:09:10 +08:00
# else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
1994-08-19 21:13:48 +08:00
1998-03-15 19:09:10 +08:00
# include <errno.h>
1994-08-20 01:01:45 +08:00
1994-08-19 21:13:48 +08:00
int
1998-12-07 11:12:10 +08:00
ftruncate (int fd, off_t length)
1994-08-19 21:13:48 +08:00
{
errno = EIO;
return -1;
}
1998-03-15 19:09:10 +08:00
# endif /* not HAVE_CHSIZE */
# endif /* not F_FREESP */
1994-08-19 21:13:48 +08:00
#endif /* not F_CHSIZE */