How can a file be truncated on System V??

Steve Alexander stevea at laidbak.UUCP
Fri May 5 00:33:46 AEST 1989


/*
 * This works only on System V 3.1 and 3.2, and relies on an
 * undocumented fcntl.  Use this at your own risk.  There are no guarantees
 * that this will remain in V.4, especially since I could find no commands
 * that use it.
 */

#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

extern void exit();

main(argc, argv)
	int	argc;
	char	**argv;
{
	int		f, i, r;
	int		trunclen, maxlen;
	char		buf[1024];

	if (argc < 4)
		error("usage: f file maxlen trunclen");

	maxlen = atoi(argv[2]);	
	maxlen /= sizeof(buf);

	trunclen = atoi(argv[3]);	

	f = open(argv[1], O_RDWR|O_CREAT, 0644);
	if (f < 0)
		error("open");

	/* write maxlen * 1024 bytes */

	for (i = 0; i < maxlen; i++)
		if (write(f, buf, sizeof(buf)) < 0)
			error("write");

	/* truncate to trunclen */
	r = ftruncate(f, trunclen);
	if (r < 0)
		error("ftruncate");
	
	r = close(f);
	if (r < 0)
		error("close");

	exit(0);
/*NOTREACHED*/
}

int
ftruncate(f, l)
	int	f;
	int	l;
{
	struct	flock	fl;

	fl.l_whence = 0;
	fl.l_len = 0;
	fl.l_start = l;

	return fcntl(f, F_FREESP, &fl);
}

error(s)
	char	*s;
{
	extern void perror();
	if (errno)
		perror(s);
	else
		(void)fprintf(stderr,"%s\n",s);
	exit(1);
}

-- 
Steve Alexander, TCP/IP Development | stevea%laidbak at sun.com
Lachman Associates, Inc.            | ...!sun!laidbak!stevea



More information about the Comp.unix.wizards mailing list