v0.4.0
Files · Lesson 19.10

Temporary file

Source
Create a scratch file with an unguessable name that is deleted when you are done with it.
You'll need: Metadata, Destructor, Move

A temporary file is scratch space with a name: somewhere to put data too big for memory, or a file to hand to another program. Two things make it harder than opening any file. The name must not clash with another file, and must not be guessable. And the file must not be left behind when the program is done with it — not even when the program leaves early through a thrown error.

A name nobody can predict

If another program could predict the name, it could create that name first — perhaps as a link to some other file — and this program would write straight through it. So TemporaryFile builds the name from a prefix plus 16 random hex digits, and creates the file only if nothing by that name exists yet; a collision just means the next random name is tried.

func Create(allocator, directory: Path, prefix: char8[..]) -> TemporaryFile throws IoError
var scratch = try TemporaryFile(allocator, directory, "draft-");
try WriteAll(scratch.file, "work in progress");
PrintLine("created            {}", scratch.AsPath().FileName() ?? OsStringView());

The name comes out as draft- and sixteen hex digits, different on every run. scratch.file is an ordinary open File, opened for both reading and writing, and AsPath lends the full path.

The directory is up to you. FileSystem::TemporaryDirectory returns the system's own folder for such files; this program uses the package's Bin/ folder instead, so you can watch what happens there.

Three ways to finish

A TemporaryFile owns both the open file and its name, so it decides what happens to them:

flowchart LR
    c["`TemporaryFile`"] --> use["write, read,<br/>hand on the name"]
    use --> close["`try Close(allocator)`"]
    use --> drop["dropped without `Close`:<br/>an early return, an error"]
    use --> keep["`try Keep()`"]
    close --> gone1["closed and deleted;<br/>a failed delete is thrown"]
    drop --> gone2["the destructor deletes it;<br/>a failure goes unreported"]
    keep --> stays["closed, and the file stays;<br/>the value gives up its name"]
EndingThe file afterwardsA failed delete is…
try Close(allocator)deletedthrown, as an IoError
droppeddeletedsilently ignored
try Keep()kept— nothing is deleted

Exists checks the outcome. It asks for the file's metadata with try?, which drops any error and leaves an optional, so "is there an answer?" becomes a presence test with is:

func Exists(allocator: Allocator, path: Path) -> bool {
    let info = try? MetadataOf(allocator, path, true);
    return info is .Some(_);
}

Closing: remember the name first

After Close, the value no longer has a name — its AsPath is empty. To check that the file is gone, the program copies the name into a PathBuffer of its own before closing:

var name = PathBuffer::FromPath(allocator, scratch.AsPath());
try scratch.Close(allocator);
PrintLine("exists after Close {}", Exists(allocator, name.AsPath()));

Close closes the file, deletes it, and throws if the deletion did not work.

Dropping: the destructor cleans up

Forgotten creates a temporary file, writes to it, and returns without closing it:

func Forgotten(allocator: Allocator, directory: Path) -> PathBuffer throws IoError {
    var scratch = try TemporaryFile(allocator, directory, "draft-");
    try WriteAll(scratch.file, "never finished");
    var name = PathBuffer::FromPath(allocator, scratch.AsPath());
    return move name;
}

When Forgotten returns, scratch goes out of scope and its destructor deletes the file. The same happens if any try in the function passes an error on, which is the point: no path out of the function leaves the file behind. The name comes back as a PathBuffer moved out with move name, as in Move, and Main confirms the file no longer exists.

The safety net has the same limit as the one in Buffered I/O: no error may leave a destructor, so a delete that fails there goes unnoticed. Call Close when you want to know.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// A temporary file is scratch space with a name: somewhere to put data that is too big for
// memory, or a name to hand to another program. Two things make that harder than it sounds.
//
// The name must not clash, and must not be guessable. If another program could predict it, it
// could create that name first, perhaps as a link to some other file, and this program would
// write through it. `TemporaryFile` builds the name from a prefix plus 16 random hex
// digits, and creates the file only if nothing by that name exists yet.
//
//     func TemporaryFile(allocator, directory: Path, prefix: char8[..]) -> Self throws IoError
//
// And the file must not be left behind. A `TemporaryFile` owns both the open file and its name.
// `Close` closes and deletes it, and throws if the deletion did not work. If the value is
// dropped without `Close`, its destructor deletes the file anyway, on early returns and error
// paths too, but no error may leave a destructor, so it stays quiet about one. `Keep`
// closes the file and gives up the name, for a file that should outlive the value.
//
// `FileSystem::TemporaryDirectory` returns the system's folder for such files. This program
// uses this package's own `Bin/` folder instead. The name is random, so it differs on every run.
import Allocator::{ Allocator, SystemAllocator };
import FileSystem::{ MetadataOf, TemporaryFile };
import Io::{ IoError, PrintLine, WriteAll };
import Path::{ OsString, OsStringView, Path, PathBuffer };

// `try?` drops any error and leaves an optional, so "is there an answer?" is a presence test.
func Exists(allocator: Allocator, path: Path) -> bool {
    let info = try? MetadataOf(allocator, path, true);
    return info is .Some(_);
}

// Creates a temporary file, writes to it, and returns without closing it.
func Forgotten(allocator: Allocator, directory: Path) -> PathBuffer throws IoError {
    var scratch = try TemporaryFile(allocator, directory, "draft-");
    try WriteAll(scratch.file, "never finished");
    var name = PathBuffer::FromPath(allocator, scratch.AsPath());
    return move name;
}

func Main() throws IoError {
    let allocator = SystemAllocator();
    var holder = OsString::FromText(allocator, "Bin");
    let directory = Path::FromView(holder.View());

    var scratch = try TemporaryFile(allocator, directory, "draft-");
    // `file` is an ordinary open `File`, opened for reading and writing.
    try WriteAll(scratch.file, "work in progress");
    PrintLine("created            {}", scratch.AsPath().FileName() ?? OsStringView());
    PrintLine("exists while held  {}", Exists(allocator, scratch.AsPath()));

    // Remember the name, because after `Close` the value no longer has one.
    var name = PathBuffer::FromPath(allocator, scratch.AsPath());
    try scratch.Close(allocator);
    PrintLine("exists after Close {}", Exists(allocator, name.AsPath()));

    let forgotten = try Forgotten(allocator, directory);
    PrintLine("exists after drop  {}", Exists(allocator, forgotten.AsPath()));
}

Besides Io, its Rux.toml lists Allocator, FileSystem and Path under [Dependencies].

Run it

cd Examples/Files/TemporaryFile
rux run
created            draft-08bf264c6b30a0cc
exists while held  true
exists after Close false
exists after drop  false

Common mistakes

Try it yourself

  1. Replace try scratch.Close(allocator) with try scratch.Keep(). Does the file survive the program? Look in Bin/, and delete it by hand afterwards.
  2. Create the file in the system's folder instead: var temporary = try TemporaryDirectory(allocator); gives a PathBuffer, and temporary.AsPath() is the directory.
  3. Make Forgotten fail on purpose after writing — for example with throw IoError::Of(IoErrorKind::Other); — so that the program ends with status 1. Is a draft- file left in Bin/ afterwards?
  4. Create two temporary files with the same prefix and print both names.

Learn more

  • Destructor — what runs when scratch goes out of scope
  • Move — returning the PathBuffer with move
  • Metadata — how Exists asks whether a file is there
  • Atomic file — a temporary file put to work: replacing another file whole