1
0
mirror of git://git.sv.gnu.org/coreutils.git synced 2026-02-26 17:16:01 +02:00
Files
coreutils/lib/ftruncate.c

96 lines
1.6 KiB
C
Raw Normal View History

1992-10-31 20:42:48 +00:00
/* ftruncate emulations that work on some System V's.
1994-08-19 13:13:48 +00:00
This file is in the public domain. */
1998-03-15 11:09:10 +00:00
#if HAVE_CONFIG_H
# include <config.h>
1994-08-19 13:13:48 +00:00
#endif
1992-10-31 20:42:48 +00:00
#include <sys/types.h>
#include <fcntl.h>
#ifdef F_CHSIZE
1994-08-19 13:13:48 +00:00
1992-10-31 20:42:48 +00:00
int
1998-12-07 03:12:10 +00:00
ftruncate (int fd, off_t length)
1992-10-31 20:42:48 +00:00
{
return fcntl (fd, F_CHSIZE, length);
}
1994-08-19 13:13:48 +00:00
#else /* not F_CHSIZE */
1998-03-15 11:09:10 +00:00
# ifdef F_FREESP
1994-08-19 13:13:48 +00:00
/* By William Kucharski <kucharsk@netcom.com>. */
1992-10-31 20:42:48 +00:00
1998-03-15 11:09:10 +00:00
# include <sys/stat.h>
# include <errno.h>
# if HAVE_UNISTD_H
# include <unistd.h>
# endif
1992-10-31 20:42:48 +00:00
int
1998-12-07 03:12:10 +00:00
ftruncate (int fd, off_t length)
1992-10-31 20:42:48 +00: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 13:13:48 +00:00
1992-10-31 20:42:48 +00:00
/* Truncate length. */
1994-08-19 13:13:48 +00:00
1992-10-31 20:42:48 +00:00
fl.l_whence = 0;
fl.l_len = 0;
fl.l_start = length;
1994-08-19 13:13:48 +00: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-10-31 20:42:48 +00:00
if (fcntl (fd, F_FREESP, &fl) < 0)
return -1;
}
return 0;
}
1994-08-19 13:13:48 +00:00
1998-03-15 11:09:10 +00:00
# else /* not F_CHSIZE nor F_FREESP */
# if HAVE_CHSIZE
1994-08-19 13:13:48 +00:00
1992-10-31 20:42:48 +00:00
int
1998-12-07 03:12:10 +00:00
ftruncate (int fd, off_t length)
1992-10-31 20:42:48 +00:00
{
return chsize (fd, length);
}
1994-08-19 13:13:48 +00:00
1998-03-15 11:09:10 +00:00
# else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
1994-08-19 13:13:48 +00:00
1998-03-15 11:09:10 +00:00
# include <errno.h>
# ifndef errno
1994-08-19 17:01:45 +00:00
extern int errno;
1998-03-15 11:09:10 +00:00
# endif
1994-08-19 17:01:45 +00:00
1994-08-19 13:13:48 +00:00
int
1998-12-07 03:12:10 +00:00
ftruncate (int fd, off_t length)
1994-08-19 13:13:48 +00:00
{
errno = EIO;
return -1;
}
1998-03-15 11:09:10 +00:00
# endif /* not HAVE_CHSIZE */
# endif /* not F_FREESP */
1994-08-19 13:13:48 +00:00
#endif /* not F_CHSIZE */