Temporary Files And Directories in Elixir

Our program demonstrates how to work with temporary files and directories in Elixir. Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

defmodule TempFilesAndDirectories do
  def run do
    # The easiest way to create a temporary file is by using
    # :tempfile.open/2. It creates a file and opens it for
    # reading and writing. We provide 'sample' as the prefix,
    # and it will create the file in the default location for our OS.
    {:ok, {fd, path}} = :tempfile.open('sample')

    # Display the name of the temporary file. On
    # Unix-based OSes the directory will likely be /tmp.
    # The file name starts with the prefix given as the
    # first argument to :tempfile.open/2 and the rest
    # is chosen automatically to ensure that concurrent
    # calls will always create different file names.
    IO.puts("Temp file name: #{path}")

    # Clean up the file after we're done. The OS is
    # likely to clean up temporary files by itself after
    # some time, but it's good practice to do this
    # explicitly.
    :ok = :file.close(fd)
    :ok = :file.delete(path)

    # We can write some data to the file.
    :ok = :file.write_file(path, <<1, 2, 3, 4>>)

    # If we intend to write many temporary files, we may
    # prefer to create a temporary directory.
    # :temp.mkdir/1 creates a temporary directory and
    # returns its name.
    {:ok, temp_dir} = :temp.mkdir('sampledir')
    IO.puts("Temp dir name: #{temp_dir}")

    # Now we can synthesize temporary file names by
    # prefixing them with our temporary directory.
    file_path = Path.join(temp_dir, "file1")
    :ok = :file.write_file(file_path, <<1, 2>>)

    # Clean up the directory after we're done.
    :ok = :file.del_dir_r(temp_dir)
  end
end

TempFilesAndDirectories.run()

To run the program:

$ elixir temp_files_and_directories.exs
Temp file name: /tmp/sample20230515-1234-abcdef
Temp dir name: /tmp/sampledir20230515-1234-ghijkl

In this Elixir version:

  1. We use :tempfile.open/2 to create a temporary file, which is similar to os.CreateTemp in Go.
  2. For temporary directories, we use :temp.mkdir/1, which is analogous to os.MkdirTemp in Go.
  3. File operations are performed using the :file module, which provides functions similar to those in Go’s os package.
  4. We use Path.join/2 to create file paths, which is similar to filepath.Join in Go.
  5. Error handling in Elixir is typically done through pattern matching on return values, rather than explicit error checks like in Go.

This example demonstrates how to create and manage temporary files and directories in Elixir, providing similar functionality to the original Go code.