truncate.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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"
  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. //kbuild:lib-$(CONFIG_TRUNCATE) += truncate.o
  15. //applet:IF_TRUNCATE(APPLET_NOFORK(truncate, truncate, BB_DIR_USR_BIN, BB_SUID_DROP, truncate))
  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 the given size\n"
  20. //usage: "\n -c Do not create files"
  21. //usage: "\n -s SIZE Truncate to 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. opt_complementary = "s:-1";
  45. opts = getopt32(argv, "cs:", &size_str);
  46. if (!(opts & OPT_NOCREATE))
  47. flags |= O_CREAT;
  48. // TODO: coreutils 8.17 also support "m" (lowercase) suffix
  49. // with truncate, but not with dd!
  50. // We share kMG_suffixes[], so we can't make both tools
  51. // compatible at once...
  52. size = XATOU_SFX(size_str, kMG_suffixes);
  53. argv += optind;
  54. while (*argv) {
  55. int fd = open(*argv, flags, 0666);
  56. if (fd < 0) {
  57. if (errno != ENOENT || !(opts & OPT_NOCREATE)) {
  58. bb_perror_msg("%s: open", *argv);
  59. ret = EXIT_FAILURE;
  60. }
  61. /* else: ENOENT && OPT_NOCREATE:
  62. * do not report error, exitcode is also 0.
  63. */
  64. } else {
  65. if (ftruncate(fd, size) == -1) {
  66. bb_perror_msg("%s: truncate", *argv);
  67. ret = EXIT_FAILURE;
  68. }
  69. xclose(fd);
  70. }
  71. ++argv;
  72. }
  73. return ret;
  74. }