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