stress-truncate.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Random.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <fcntl.h>
  9. #include <inttypes.h>
  10. #include <sys/stat.h>
  11. #include <unistd.h>
  12. int main(int argc, char** argv)
  13. {
  14. const char* target = nullptr;
  15. int max_file_size = 1024 * 1024;
  16. int count = 1024;
  17. Core::ArgsParser args_parser;
  18. args_parser.add_option(max_file_size, "Maximum file size to generate", "max-size", 's', "size");
  19. args_parser.add_option(count, "Number of truncations to run", "number", 'n', "number");
  20. args_parser.add_positional_argument(target, "Target file path", "target");
  21. args_parser.parse(argc, argv);
  22. int fd = creat(target, 0666);
  23. if (fd < 0) {
  24. perror("Couldn't create target file");
  25. return EXIT_FAILURE;
  26. }
  27. close(fd);
  28. for (int i = 0; i < count; i++) {
  29. auto new_file_size = AK::get_random<uint64_t>() % (max_file_size + 1);
  30. printf("(%d/%d)\tTruncating to %" PRIu64 " bytes...\n", i + 1, count, new_file_size);
  31. if (truncate(target, new_file_size) < 0) {
  32. perror("Couldn't truncate target file");
  33. return EXIT_FAILURE;
  34. }
  35. }
  36. if (unlink(target) < 0) {
  37. perror("Couldn't remove target file");
  38. return EXIT_FAILURE;
  39. }
  40. return EXIT_SUCCESS;
  41. }