Directories in Elixir
Here’s the translation of the Go code to Elixir, along with explanations in Markdown format suitable for Hugo:
Elixir has several useful functions for working with directories in the file system.
defmodule Directories do
def main do
# Create a new sub-directory in the current working directory.
File.mkdir("subdir")
# When creating temporary directories, it's good practice to
# ensure their removal. File.rm_rf will delete a whole directory
# tree (similarly to `rm -rf`).
on_exit = fn -> File.rm_rf("subdir") end
# Helper function to create a new empty file.
create_empty_file = fn name ->
File.write!(name, "")
end
create_empty_file.("subdir/file1")
# We can create a hierarchy of directories, including parents
# with File.mkdir_p. This is similar to the command-line `mkdir -p`.
File.mkdir_p("subdir/parent/child")
create_empty_file.("subdir/parent/file2")
create_empty_file.("subdir/parent/file3")
create_empty_file.("subdir/parent/child/file4")
# File.ls lists directory contents, returning a list of file names.
{:ok, entries} = File.ls("subdir/parent")
IO.puts("Listing subdir/parent")
Enum.each(entries, fn entry ->
is_dir = File.dir?("subdir/parent/#{entry}")
IO.puts(" #{entry} #{is_dir}")
end)
# File.cd lets us change the current working directory,
# similarly to `cd`.
File.cd("subdir/parent/child")
# Now we'll see the contents of `subdir/parent/child`
# when listing the *current* directory.
{:ok, entries} = File.ls()
IO.puts("Listing subdir/parent/child")
Enum.each(entries, fn entry ->
is_dir = File.dir?(entry)
IO.puts(" #{entry} #{is_dir}")
end)
# `cd` back to where we started.
File.cd("../../..")
# We can also visit a directory *recursively*,
# including all its sub-directories. File.ls_r returns
# a list of all files and directories recursively.
IO.puts("Visiting subdir")
{:ok, paths} = File.ls_r("subdir")
Enum.each(paths, fn path ->
is_dir = File.dir?("subdir/#{path}")
IO.puts(" #{path} #{is_dir}")
end)
# Call the cleanup function
on_exit.()
end
end
Directories.main()
To run the program, save it as directories.exs
and use elixir
:
$ elixir directories.exs
Listing subdir/parent
child true
file2 false
file3 false
Listing subdir/parent/child
file4 false
Visiting subdir
file1 false
parent true
parent/child true
parent/child/file4 false
parent/file2 false
parent/file3 false
This Elixir code demonstrates working with directories, including creating directories, listing contents, changing the current directory, and recursively walking a directory tree. The structure and functionality closely mirror the original Go example, adapted to Elixir’s syntax and standard library functions.
Note that Elixir uses the File
module for most file system operations, and some concepts (like defer
) are handled differently (using anonymous functions in this case). The recursive directory walk is implemented using File.ls_r/1
instead of a custom callback function.