1
0
mirror of git://git.sv.gnu.org/coreutils.git synced 2026-04-19 18:26:32 +02:00
Files
coreutils/lib/ftruncate.c

104 lines
1.7 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. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#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
ftruncate (fd, length)
int fd;
off_t length;
{
return fcntl (fd, F_CHSIZE, length);
}
1994-08-19 13:13:48 +00:00
#else /* not F_CHSIZE */
1992-10-31 20:42:48 +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
#include <sys/stat.h>
1994-08-19 17:01:45 +00:00
#include <errno.h>
1994-08-19 17:05:18 +00:00
#ifdef HAVE_UNISTD_H
1992-10-31 20:42:48 +00:00
#include <unistd.h>
1994-08-19 17:05:18 +00:00
#endif
1992-10-31 20:42:48 +00:00
int
ftruncate (fd, length)
int fd;
off_t length;
{
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
#else /* not F_CHSIZE nor F_FREESP */
#ifdef HAVE_CHSIZE
1992-10-31 20:42:48 +00:00
int
ftruncate (fd, length)
int fd;
off_t length;
{
return chsize (fd, length);
}
1994-08-19 13:13:48 +00:00
#else /* not F_CHSIZE nor F_FREESP nor HAVE_CHSIZE */
1994-08-19 17:01:45 +00:00
#include <errno.h>
#ifndef errno
extern int errno;
#endif
1994-08-19 13:13:48 +00:00
int
ftruncate (fd, length)
int fd;
off_t length;
{
errno = EIO;
return -1;
}
#endif /* not HAVE_CHSIZE */
#endif /* not F_FREESP */
#endif /* not F_CHSIZE */