This introduction to working with the filesystem is grossly simplified. It does, however, cover enough to get started with most projects.
Our current working directory (in two different forms of error handling):
{:ok, cwd} = File.cwd()
{
cwd,
File.cwd!()
}
What is in that directory?
files =
[cwd, "*"]
|> Path.join()
|> Path.wildcard()
Which of these are directories?
dirs =
files
|> Enum.filter(&File.dir?/1)
First, lets come up with a filename that is highly unlikely to hurt anyone:
filename = "30c39b99-b9a8-4789-91ad-6283e43d1433"
Lets verify that it does not exist:
File.exists?(filename)
Note: Only continue if this returns false
.
{:ok, writer} = File.open(filename, [:write])
IO.write(writer, "Hello")
File.close(writer)
{:ok, appender} = File.open(filename, [:append])
IO.write(appender, ", World")
File.close(appender)
Reading of entire file:
case File.read(filename) do
{:ok, lines} ->
IO.puts(lines)
{:error, details} ->
IO.puts("Unable to read #{filename}: #{details}")
end
If the file is large, that is likely to be a bad idea. Instead the IO.read/2 function offers more control. In this case we read the first couple of characters (but there is also an option for reading a line):
{:ok, reader} = File.open(filenameThis)
reader
|> IO.read(5)
|> IO.puts()
File.close(reader)
Finally, lets clean up after ourselves:
File.rm(filename)