3
0

truncate.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Mini truncate implementation for busybox
  3. *
  4. * Copyright (C) 2015 by Ari Sundholm <ari@tuxera.com>
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. //config:config TRUNCATE
  9. //config: bool "truncate (4.2 kb)"
  10. //config: default y
  11. //config: help
  12. //config: truncate truncates files to a given size. If a file does
  13. //config: not exist, it is created unless told otherwise.
  14. //applet:IF_TRUNCATE(APPLET_NOFORK(truncate, truncate, BB_DIR_USR_BIN, BB_SUID_DROP, truncate))
  15. //kbuild:lib-$(CONFIG_TRUNCATE) += truncate.o
  16. //usage:#define truncate_trivial_usage
  17. //usage: "[-c] -s SIZE FILE..."
  18. //usage:#define truncate_full_usage "\n\n"
  19. //usage: "Truncate FILEs to SIZE\n"
  20. //usage: "\n -c Do not create files"
  21. //usage: "\n -s SIZE"
  22. //usage:
  23. //usage:#define truncate_example_usage
  24. //usage: "$ truncate -s 1G foo"
  25. #include "libbb.h"
  26. #if ENABLE_LFS
  27. # define XATOU_SFX xatoull_sfx
  28. #else
  29. # define XATOU_SFX xatoul_sfx
  30. #endif
  31. /* This is a NOFORK applet. Be very careful! */
  32. int truncate_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  33. int truncate_main(int argc UNUSED_PARAM, char **argv)
  34. {
  35. unsigned opts;
  36. int flags = O_WRONLY | O_NONBLOCK;
  37. int ret = EXIT_SUCCESS;
  38. char *size_str;
  39. off_t size;
  40. enum {
  41. OPT_NOCREATE = (1 << 0),
  42. OPT_SIZE = (1 << 1),
  43. };
  44. opts = getopt32(argv, "^" "cs:" "\0" "s:-1", &size_str);
  45. if (!(opts & OPT_NOCREATE))
  46. flags |= O_CREAT;
  47. // TODO: coreutils 8.17 also support "m" (lowercase) suffix
  48. // with truncate, but not with dd!
  49. // We share kMG_suffixes[], so we can't make both tools
  50. // compatible at once...
  51. size = XATOU_SFX(size_str, kMG_suffixes);
  52. argv += optind;
  53. while (*argv) {
  54. int fd = open(*argv, flags, 0666);
  55. if (fd < 0) {
  56. if (errno != ENOENT || !(opts & OPT_NOCREATE)) {
  57. bb_perror_msg("%s: open", *argv);
  58. ret = EXIT_FAILURE;
  59. }
  60. /* else: ENOENT && OPT_NOCREATE:
  61. * do not report error, exitcode is also 0.
  62. */
  63. } else {
  64. if (ftruncate(fd, size) == -1) {
  65. bb_perror_msg("%s: truncate", *argv);
  66. ret = EXIT_FAILURE;
  67. }
  68. xclose(fd);
  69. }
  70. ++argv;
  71. }
  72. return ret;
  73. }