xref: /freebsd/tests/sys/cddl/zfs/bin/randfree_file.c (revision e1e636193db45630c7881246d25902e57c43d24e)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 
28 #include "file_common.h"
29 
30 /*
31  * Create a file with assigned size and then free the specified
32  * section of the file
33  */
34 
35 static void usage(char *progname);
36 
37 static void
38 usage(char *progname)
39 {
40 	(void) fprintf(stderr,
41 	    "usage: %s [-l filesize] [-s start-offset]"
42 	    "[-n section-len] filename\n", progname);
43 	exit(1);
44 }
45 
46 int
47 main(int argc, char *argv[])
48 {
49 	char *filename, *buf;
50 	size_t filesize;
51 	off_t start_off, off_len;
52 	int  fd, ch;
53 	struct flock fl;
54 
55 	while ((ch = getopt(argc, argv, "l:s:n:")) != EOF) {
56 		switch (ch) {
57 		case 'l':
58 			filesize = atoll(optarg);
59 			break;
60 		case 's':
61 			start_off = atoll(optarg);
62 			break;
63 		case 'n':
64 			off_len = atoll(optarg);
65 			break;
66 		default:
67 			usage(argv[0]);
68 			break;
69 		}
70 	}
71 
72 	if (optind == argc - 1)
73 		filename = argv[optind];
74 	else
75 		usage(argv[0]);
76 
77 	buf = (char *)malloc(filesize);
78 
79 	if ((fd = open(filename, O_RDWR|O_CREAT|O_TRUNC)) < 0) {
80 		perror("open");
81 		return (1);
82 	}
83 	if (write(fd, buf, filesize) < filesize) {
84 		perror("write");
85 		return (1);
86 	}
87 #if UNSUPPORTED
88 	fl.l_whence = SEEK_SET;
89 	fl.l_start = start_off;
90 	fl.l_len = off_len;
91 	if (fcntl(fd, F_FREESP, &fl) != 0) {
92 		perror("fcntl");
93 		return (1);
94 	}
95 #else
96 	fprintf(stderr, "fcntl: F_FREESP not supported\n");
97 	return (1);
98 #endif
99 
100 	free(buf);
101 	return (0);
102 }
103