1 #pragma once 2 3 #include <c10/macros/Export.h> 4 #include <optional> 5 #include <string> 6 #include <string_view> 7 #include <utility> 8 9 namespace c10 { 10 struct C10_API TempFile { fdTempFile11 TempFile(std::string_view name, int fd = -1) noexcept : fd(fd), name(name) {} 12 TempFile(const TempFile&) = delete; TempFileTempFile13 TempFile(TempFile&& other) noexcept 14 : fd(other.fd), name(std::move(other.name)) { 15 other.fd = -1; 16 } 17 18 TempFile& operator=(const TempFile&) = delete; 19 TempFile& operator=(TempFile&& other) noexcept { 20 fd = other.fd; 21 name = std::move(other.name); 22 other.fd = -1; 23 return *this; 24 } 25 #if defined(_WIN32) 26 bool open(); 27 #endif 28 29 ~TempFile(); 30 31 int fd; 32 33 std::string name; 34 }; 35 36 struct C10_API TempDir { 37 TempDir() = delete; TempDirTempDir38 explicit TempDir(std::string_view name) noexcept : name(name) {} 39 TempDir(const TempDir&) = delete; TempDirTempDir40 TempDir(TempDir&& other) noexcept : name(std::move(other.name)) { 41 other.name.clear(); 42 } 43 44 TempDir& operator=(const TempDir&) = delete; 45 TempDir& operator=(TempDir&& other) noexcept { 46 name = std::move(other.name); 47 return *this; 48 } 49 50 ~TempDir(); 51 52 std::string name; 53 }; 54 55 /// Attempts to return a temporary file or returns `nullopt` if an error 56 /// occurred. 57 /// 58 /// The file returned follows the pattern 59 /// `<tmp-dir>/<name-prefix><random-pattern>`, where `<tmp-dir>` is the value of 60 /// the `"TMPDIR"`, `"TMP"`, `"TEMP"` or 61 /// `"TEMPDIR"` environment variable if any is set, or otherwise `/tmp`; 62 /// `<name-prefix>` is the value supplied to this function, and 63 /// `<random-pattern>` is a random sequence of numbers. 64 /// On Windows, `name_prefix` is ignored and `tmpnam_s` is used, 65 /// and no temporary file is opened. 66 C10_API std::optional<TempFile> try_make_tempfile( 67 std::string_view name_prefix = "torch-file-"); 68 69 /// Like `try_make_tempfile`, but throws an exception if a temporary file could 70 /// not be returned. 71 C10_API TempFile make_tempfile(std::string_view name_prefix = "torch-file-"); 72 73 /// Attempts to return a temporary directory or returns `nullopt` if an error 74 /// occurred. 75 /// 76 /// The directory returned follows the pattern 77 /// `<tmp-dir>/<name-prefix><random-pattern>/`, where `<tmp-dir>` is the value 78 /// of the `"TMPDIR"`, `"TMP"`, `"TEMP"` or 79 /// `"TEMPDIR"` environment variable if any is set, or otherwise `/tmp`; 80 /// `<name-prefix>` is the value supplied to this function, and 81 /// `<random-pattern>` is a random sequence of numbers. 82 /// On Windows, `name_prefix` is ignored. 83 C10_API std::optional<TempDir> try_make_tempdir( 84 std::string_view name_prefix = "torch-dir-"); 85 86 /// Like `try_make_tempdir`, but throws an exception if a temporary directory 87 /// could not be returned. 88 C10_API TempDir make_tempdir(std::string_view name_prefix = "torch-dir-"); 89 } // namespace c10 90