xref: /freebsd/sys/contrib/openzfs/tests/zfs-tests/cmd/truncate_test.c (revision 02e9120893770924227138ba49df1edb3896112a)
1 /*
2  * This file and its contents are supplied under the terms of the
3  * Common Development and Distribution License ("CDDL"), version 1.0.
4  * You may only use this file in accordance with the terms of version
5  * 1.0 of the CDDL.
6  *
7  * A full copy of the text of the CDDL should have accompanied this
8  * source.  A copy of the CDDL is also available via the Internet at
9  * http://www.illumos.org/license/CDDL.
10  */
11 
12 /*
13  * Copyright (c) 2012, 2014 by Delphix. All rights reserved.
14  * Copyright 2017, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
15  */
16 
17 #include <fcntl.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21 #include <errno.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 
25 #define	FSIZE	256*1024*1024
26 
27 static long	fsize = FSIZE;
28 static int	errflag = 0;
29 static char	*filename = NULL;
30 static int	ftruncflag = 0;
31 
32 static void parse_options(int argc, char *argv[]);
33 
34 static void
35 usage(char *execname)
36 {
37 	(void) fprintf(stderr,
38 	    "usage: %s [-s filesize] [-f] /path/to/file\n", execname);
39 	(void) exit(1);
40 }
41 
42 int
43 main(int argc, char *argv[])
44 {
45 	int fd;
46 
47 	parse_options(argc, argv);
48 
49 	if (ftruncflag) {
50 		fd = open(filename, O_RDWR|O_CREAT, 0666);
51 		if (fd < 0) {
52 			perror("open");
53 			return (1);
54 		}
55 		if (ftruncate(fd, fsize) < 0) {
56 			perror("ftruncate");
57 			return (1);
58 		}
59 		if (close(fd)) {
60 			perror("close");
61 			return (1);
62 		}
63 	} else {
64 		if (truncate(filename, fsize) < 0) {
65 			perror("truncate");
66 			return (1);
67 		}
68 	}
69 	return (0);
70 }
71 
72 static void
73 parse_options(int argc, char *argv[])
74 {
75 	int c;
76 	extern char *optarg;
77 	extern int optind, optopt;
78 
79 	while ((c = getopt(argc, argv, "s:f")) != -1) {
80 		switch (c) {
81 			case 's':
82 				fsize = atoi(optarg);
83 				break;
84 			case 'f':
85 				ftruncflag++;
86 				break;
87 			case ':':
88 				(void) fprintf(stderr,
89 				    "Option -%c requires an operand\n", optopt);
90 				errflag++;
91 				break;
92 		}
93 		if (errflag) {
94 			(void) usage(argv[0]);
95 		}
96 	}
97 
98 	if (argc <= optind) {
99 		(void) fprintf(stderr, "No filename specified\n");
100 		usage(argv[0]);
101 	}
102 	filename = argv[optind];
103 }
104