[PATCH] truncate: new applet
Ari Sundholm
ari at tuxera.com
Tue Mar 3 16:11:55 UTC 2015
I wrote this for my own purposes and cleaned it up in hopes it is useful.
Signed-off-by: Ari Sundholm <ari at tuxera.com>
---
coreutils/truncate.c | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 92 insertions(+)
create mode 100644 coreutils/truncate.c
diff --git a/coreutils/truncate.c b/coreutils/truncate.c
new file mode 100644
index 0000000..f997cd2
--- /dev/null
+++ b/coreutils/truncate.c
@@ -0,0 +1,92 @@
+/*
+ * Mini truncate implementation for busybox
+ *
+ * Copyright (C) 2015 by Ari Sundholm <ari at tuxera.com>
+ *
+ * Licensed under GPLv2 or later, see file LICENSE in this source tree.
+ */
+
+//config:config TRUNCATE
+//config: bool "truncate"
+//config: default y
+//config: help
+//config: truncate truncates files to a given size. If a file does
+//config: not exist, it is created unless told otherwise.
+
+//kbuild:lib-$(CONFIG_TRUNCATE) += truncate.o
+//applet:IF_TRUNCATE(APPLET(truncate, BB_DIR_USR_BIN, BB_SUID_DROP))
+
+//usage:#define truncate_trivial_usage
+//usage: "[-c] -s SIZE FILE..."
+//usage:#define truncate_full_usage "\n\n"
+//usage: "Truncate FILEs to the given size.\n"
+//usage: "\n -c Do not create any files."
+//usage: "\n -s SIZE Truncate to SIZE."
+//usage:
+//usage:#define truncate_example_usage
+//usage: "$ truncate -s 1G foo"
+
+#include "libbb.h"
+
+static const struct suffix_mult truncate_suffixes[] = {
+ { "c", 1 },
+ { "w", 2 },
+ { "b", 512 },
+ { "kB", 1000 },
+ { "kD", 1000 },
+ { "k", 1024 },
+ { "K", 1024 }, /* compat with coreutils dd (it also accepts KB and KD, TODO?) */
+ { "MB", 1000000 },
+ { "MD", 1000000 },
+ { "M", 1024*1024 },
+ { "GB", 1000000000 },
+ { "GD", 1000000000 },
+ { "G", 1024*1024*1024 },
+ /* "D" suffix for decimal is not in coreutils manpage, looks like it's deprecated */
+ /* coreutils also understands TPEZY suffixes for tera- and so on, with B suffix for decimal */
+ { "", 0 }
+};
+
+#if ENABLE_LFS
+# define XATOU_SFX xatoull_sfx
+#else
+# define XATOU_SFX xatoul_sfx
+#endif
+
+int truncate_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
+int truncate_main(int argc UNUSED_PARAM, char **argv) {
+ unsigned opts;
+ int flags = O_CREAT|O_RDWR;
+ int fd;
+ char *size_str;
+ off_t size;
+
+ enum {
+ OPT_NOCREATE = (1 << 0),
+ OPT_SIZE = (1 << 1),
+ };
+
+ opt_complementary = "s";
+ opts = getopt32(argv, "cs:", &size_str);
+
+ argv += optind;
+ if (!*argv) {
+ bb_error_msg("truncate: no files specified!\n");
+ return 1;
+ }
+
+ if (opts & OPT_NOCREATE)
+ flags = O_RDWR;
+
+ size = XATOU_SFX(size_str, truncate_suffixes);
+
+ while (*argv) {
+ fd = xopen(*argv, flags);
+ if (ftruncate(fd, size) == -1)
+ bb_perror_msg_and_die("ftruncate failed");
+ xclose(fd);
+ ++argv;
+ }
+
+ return 0;
+}
--
1.9.1
More information about the busybox
mailing list