ftruncate(2) for System V.3.2 needed

William Kucharski kucharsk at uts.amdahl.com
Sat Jul 8 08:10:57 AEST 1989


In article <1132 at ssp15.idca.tds.philips.nl> jos at idca.tds.PHILIPS.nl (Jos Vos) writes:
 >I need the ftruncate(2) function from BSD4.3 UNIX on System V.3.2.
 >For non-BSD-manual-owners, here's the description of ftruncate(2)...

I can see that this one is going to make it into the "frequently asked
question" section...

========[Cut Here]========

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int
ftruncate(fd, length)
int     fd;     /* file descriptor */
off_t   length; /* length to set file to */
{
        extern  long    lseek();

        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 {
                /* truncate length */

                fl.l_whence = 0;
                fl.l_len = 0;
                fl.l_start = length;
                fl.l_type = F_WRLCK;    /* write lock on file space */

                /*
                 * This relies on the UNDOCUMENTED F_FREESP argument to
                 * fcntl(2), which truncates the file so that it ends at the
                 * position indicated by fl.l_start.
                 *
                 * Will minor miracles never cease?
                 */

		if (fcntl(fd, F_FREESP, &fl) < 0)
			return(-1);

        }

        return(0);
}

-- 
					William Kucharski

ARPA: kucharsk at uts.amdahl.com
UUCP: ...!{ames,decwrl,sun,uunet}!amdahl!kucharsk

Disclaimer:  The opinions expressed above are my own, and may not agree with
	     those of any other sentient being, not to mention those of my 
	     employer.  So there.



More information about the Comp.unix.wizards mailing list