Skip to content

feat(io): modernize sight::core::tools::System::getTemporaryFolder()

Description

Rework temporary directory / file management. Provides a unique, per process temporary directory which is cleaned at program exit and on-demand temporary subdirectories / files, cleaned at object destruction.

Based on RAII, the new implementation ensures 3 things:

  • thread safe and process safe (almost no possible name collision when using file name, 100% guaranteed for directory or when using streams)
  • path are kept short (to avoid 256 characters limit on Windows)
  • Simple to use. RAII let you forget about cleaning, many convenience operators to use it like a std::filesystem::path, or a std::string, or std::ofstream.

Some samples:

{
  core::tools::TemporaryDirectory tmpDir;

  // display something like `/tmp/sd5d/erf`
  std::cout << tmpDir.path() << std::endl;

  // It can be used in path or string easily:
  const std::filesystem::path subdir = tmpDir / "a_sub_path";
  std::cout << subdir.string() << std::endl;
}

// tmpDir directory (`/tmp/sd5d/erf`) is deleted here...

{
  // will create a temporary file somewhere, but close it, so subsequent call will not be able to use the same path
  core::tools::TemporaryFile tmpFile;
 
  // You can do that thanks to std::string() conversion
  std::ofstream ofs(tmpFile);
  ofs << "Hello";
}

// tmpFile is deleted

{
  // will create a temporary file somewhere, **but will keep it OPEN**. This is the safest mode (and the more secure as no file injection should be possible)
  core::tools::TemporaryFile tmpFile(std::io_base::out);
 
  // Now you can directly use it as a ostream thanks to &std::ostream conversion
  tmpFile << "Hello";
}

// tmpFile is deleted (and it stream closed)


// For Compatibility reason and som usage, it is possible to access the shared "root" temporary directory, that is only cleaned at program exit (exception should be managed, but of course not "hard" failures like power supply failures)
// The directory is guaranteed to exist
const std::filesystem::path root = core::tools::TemporaryFile::path();

// display something like `/tmp/sd5d`
std::cout << root.string() << std::endl;

See unit test for other examples...

Closes #1053 (closed)

How to test it?

Unit tests...

Edited by Didier WECKMANN

Merge request reports