TempFile.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Copyright (c) 2020-2023, the SerenityOS developers.
  3. * Copyright (c) 2023, Cameron Youell <cameronyouell@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibCore/System.h>
  8. #include <LibFileSystem/FileSystem.h>
  9. #include <LibFileSystem/TempFile.h>
  10. namespace FileSystem {
  11. TempFile::~TempFile()
  12. {
  13. // Temporary files aren't removed by anyone else, so we must do it ourselves.
  14. auto recursion_mode = RecursionMode::Disallowed;
  15. if (m_type == Type::Directory)
  16. recursion_mode = RecursionMode::Allowed;
  17. auto result = FileSystem::remove(m_path, recursion_mode);
  18. if (result.is_error())
  19. warnln("Removal of temporary file failed '{}': {}", m_path, result.error().string_literal());
  20. }
  21. ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_directory()
  22. {
  23. char pattern[] = "/tmp/tmp.XXXXXX";
  24. auto path = TRY(Core::System::mkdtemp(pattern));
  25. return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::Directory, path));
  26. }
  27. ErrorOr<NonnullOwnPtr<TempFile>> TempFile::create_temp_file()
  28. {
  29. char file_path[] = "/tmp/tmp.XXXXXX";
  30. TRY(Core::System::mkstemp(file_path));
  31. auto string = TRY(String::from_utf8({ file_path, sizeof file_path }));
  32. return adopt_nonnull_own_or_enomem(new (nothrow) TempFile(Type::File, string));
  33. }
  34. }