File

This module contains functions to manipulate files.

Some of those functions are low-level, allowing the user to interact with the file or IO devices, like open/2, copy/3 and others. This module also provides higher level functions that works with filenames and have their naming based on UNIX variants. For example, one can copy a file via cp/3 and remove files and directories recursively via rm_rf/1

In order to write and read files, one must use the functions in the IO module. By default, a file is opened in binary mode which requires the functions IO.binread/2 and IO.binwrite/2 to interact with the file. A developer may pass :utf8 as an option when opening the file, then the slower IO.read/2 and IO.write/2 functions must be used as they are responsible for doing the proper conversions and data guarantees.

Most of the functions in this module return :ok or { :ok, result } in case of success, { :error, reason } otherwise. Those function are also followed by a variant that ends with ! which returns the result (without the { :ok, result } tuple) in case of success or raises an exception in case it fails. For example:

File.read("hello.txt")
#=> { :ok, "World" }

File.read("invalid.txt")
#=> { :error, :enoent }

File.read!("hello.txt")
#=> "World"

File.read!("invalid.txt")
#=> raises File.Error

In general, a developer should use the former in case he wants to react if the file does not exist. The latter should be used when the developer expects his software to fail in case the file cannot be read (i.e. it is literally an exception).

Source

Summary

cd!(path)

The same as cd/1, but raises an exception if it fails

cd!(path, function)

Changes the current directory to the given path, executes the given function and then revert back to the previous path regardless if there is an exception

cd(path)

Sets the current working directory. Returns :ok if successful, { :error, reason } otherwise

chgrp!(file, gid)

Same as chgrp/2, but raises an exception in case of failure. Otherwise :ok

chgrp(file, gid)

Changes the user group given by the group id gid for a given file. Returns :ok on success, or {:error, reason} on failure

chmod!(file, mode)

Same as chmod/2, but raises an exception in case of failure. Otherwise :ok

chmod(file, mode)

Changes the unix file mode for a given file. Returns :ok on success, or {:error, reason} on failure

chown!(file, uid)

Same as chown/2, but raises an exception in case of failure. Otherwise :ok

chown(file, uid)

Changes the owner given by the user id uid for a given file. Returns :ok on success, or {:error, reason} on failure

close(io_device)

Closes the file referenced by io_device. It mostly returns :ok, except for some severe errors such as out of memory

copy!(source, destination, bytes_count \\ :infinity)

The same as copy/3 but raises an File.CopyError if it fails. Returns the bytes_copied otherwise

copy(source, destination, bytes_count \\ :infinity)

Copies the contents of source to destination

cp!(source, destination, callback \\ fn _, _ -> true end)

The same as cp/3, but raises File.CopyError if it fails. Returns the list of copied files otherwise

cp(source, destination, callback \\ fn _, _ -> true end)

Copies the contents in source to destination preserving its mode

cp_r!(source, destination, callback \\ fn _, _ -> true end)

The same as cp_r/3, but raises File.CopyError if it fails. Returns the list of copied files otherwise

cp_r(source, destination, callback \\ fn _, _ -> true end)

Copies the contents in source to destination

cwd!()

The same as cwd/0, but raises an exception if it fails

cwd()

Gets the current working directory. In rare circumstances, this function can fail on Unix. It may happen if read permission does not exist for the parent directories of the current directory. For this reason, returns { :ok, cwd } in case of success, { :error, reason } otherwise

dir?(path)

Returns true if the path is a directory

exists?(path)

Returns true if the given path exists. It can be regular file, directory, socket, symbolic link, named pipe or device file

ls!(dir \\ ".")

The same as ls/1 but raises File.Error in case of an error

ls(path \\ ".")

Returns list of files in the given directory

mkdir!(path)

Same as mkdir/1, but raises an exception in case of failure. Otherwise :ok

mkdir(path)

Tries to create the directory path. Missing parent directories are not created. Returns :ok if successful, or {:error, reason} if an error occurs

mkdir_p!(path)

Same as mkdir_p/1, but raises an exception in case of failure. Otherwise :ok

mkdir_p(path)

Tries to create the directory path. Missing parent directories are created. Returns :ok if successful, or {:error, reason} if an error occurs

open!(path, modes \\ [])

Same as open/2 but raises an error if file could not be opened. Returns the io_device otherwise

open!(path, modes, function)

Same as open/3 but raises an error if file could not be opened. Returns the function result otherwise

open(path, modes \\ [])

Opens the given path according to the given list of modes

open(path, modes, function)

Similar to open/2 but expects a function as last argument

read!(path)

Returns binary with the contents of the given filename or raises File.Error if an error occurs

read(path)

Returns {:ok, binary}, where binary is a binary data object that contains the contents of path, or {:error, reason} if an error occurs

regular?(path)

Returns true if the path is a regular file

rm!(path)

Same as rm/1, but raises an exception in case of failure. Otherwise :ok

rm(path)

Tries to delete the file path. Returns :ok if successful, or {:error, reason} if an error occurs

rm_rf!(path)

Same as rm_rf/1 but raises File.Error in case of failures, otherwise the list of files or directories removed

rm_rf(path)

Remove files and directories recursively at the given path. Symlinks are not followed but simply removed, non-existing files are simply ignored (i.e. doesn't make this function fail)

rmdir!(path)

Same as rmdir/1, but raises an exception in case of failure. Otherwise :ok

rmdir(path)

Tries to delete the dir at path. Returns :ok if successful, or {:error, reason} if an error occurs

stat!(path, opts \\ [])

Same as stat/2 but returns the File.Stat directly and throws File.Error if an error is returned

stat(path, opts \\ [])

Returns information about the path. If it exists, it returns a { :ok, info } tuple, where info is a File.Info record. Retuns { :error, reason } with the same reasons as read/1 if a failure occurs

stream!(path, modes \\ [], line_or_bytes \\ :line)

Opens the file at the given path with the given modes and returns a stream for each :line (default) or for a given number of bytes given by line_or_bytes

stream_to!(stream, path, modes \\ [])

Receives a stream and returns a new stream that will open the file at the given path for write with the extra modes and write each value to the file

touch!(path, time \\ :calendar.local_time())

Same as touch/2 but raises an exception if it fails. Returns :ok otherwise

touch(path, time \\ :calendar.local_time())

Updates modification time (mtime) and access time (atime) of the given file. File is created if it doesn’t exist

write!(path, content, modes \\ [])

Same as write/3 but raises an exception if it fails, returns :ok otherwise

write(path, content, modes \\ [])

Writes content to the file path. The file is created if it does not exist. If it exists, the previous contents are overwritten. Returns :ok if successful, or {:error, reason} if an error occurs

write_stat!(path, stat, opts \\ [])

Same as write_stat/3 but raises an exception if it fails. Returns :ok otherwise

write_stat(path, stat, opts \\ [])

Writes the given File.Stat back to the filesystem at the given path. Returns :ok or { :error, reason }

Functions

cd(path)

Sets the current working directory. Returns :ok if successful, { :error, reason } otherwise.

Source
cd!(path)

The same as cd/1, but raises an exception if it fails.

Source
cd!(path, function)

Changes the current directory to the given path, executes the given function and then revert back to the previous path regardless if there is an exception.

Raises an error if retrieving or changing the current directory fails.

Source
chgrp(file, gid)

Changes the user group given by the group id gid for a given file. Returns :ok on success, or {:error, reason} on failure.

Source
chgrp!(file, gid)

Same as chgrp/2, but raises an exception in case of failure. Otherwise :ok.

Source
chmod(file, mode)

Changes the unix file mode for a given file. Returns :ok on success, or {:error, reason} on failure.

Source
chmod!(file, mode)

Same as chmod/2, but raises an exception in case of failure. Otherwise :ok.

Source
chown(file, uid)

Changes the owner given by the user id uid for a given file. Returns :ok on success, or {:error, reason} on failure.

Source
chown!(file, uid)

Same as chown/2, but raises an exception in case of failure. Otherwise :ok.

Source
close(io_device)

Closes the file referenced by io_device. It mostly returns :ok, except for some severe errors such as out of memory.

Note that if the option :delayed_write was used when opening the file, close/1 might return an old write error and not even try to close the file. See open/2.

Source
copy(source, destination, bytes_count \\ :infinity)

Copies the contents of source to destination.

Both parameters can be a filename or an io device opened with open/2. bytes_count specifies the number of bytes to copy, the default being :infinity.

If file destination already exists, it is overwritten by the contents in source.

Returns { :ok, bytes_copied } if successful, { :error, reason } otherwise.

Compared to the cp/3, this function is more low-level, allowing a copy from device to device limited by a number of bytes. On the other hand, cp/3 performs more extensive checks on both source and destination and it also preserves the file mode after copy.

Typical error reasons are the same as in open/2, read/1 and write/3.

Source
copy!(source, destination, bytes_count \\ :infinity)

The same as copy/3 but raises an File.CopyError if it fails. Returns the bytes_copied otherwise.

Source
cp(source, destination, callback \\ fn _, _ -> true end)

Copies the contents in source to destination preserving its mode.

If a file already exists in the destination, it invokes a callback which should return true if the existing file should be overwritten, false otherwise. It defaults to return true.

It returns :ok in case of success, returns { :error, reason } otherwise.

If you want to copy contents from an io device to another device or do a straight copy from a source to a destination without preserving modes, check copy/3 instead.

Note: The command cp in Unix systems behaves differently depending if destination is an existing directory or not. We have chosen to explicitly disallow this behaviour. If destination is a directory, an error will be returned.

Source
cp!(source, destination, callback \\ fn _, _ -> true end)

The same as cp/3, but raises File.CopyError if it fails. Returns the list of copied files otherwise.

Source
cp_r(source, destination, callback \\ fn _, _ -> true end)

Copies the contents in source to destination.

If the source is a file, it copies source to destination. If the source is a directory, it copies the contents inside source into the destination.

If a file already exists in the destination, it invokes a callback which should return true if the existing file should be overwritten, false otherwise. It defaults to return true.

If a directory already exists in the destination where a file is meant to be (or otherwise), this function will fail.

This function may fail while copying files, in such cases, it will leave the destination directory in a dirty state, where already copied files won't be removed.

It returns { :ok, files_and_directories } in case of success with all files and directories copied in no specific order, { :error, reason } otherwise.

Note: The command cp in Unix systems behaves differently depending if destination is an existing directory or not. We have chosen to explicitly disallow this behaviour.

Examples

# Copies "a.txt" to "tmp"
File.cp_r "a.txt", "tmp.txt"

# Copies all files in "samples" to "tmp"
File.cp_r "samples", "tmp"

# Same as before, but asks the user how to proceed in case of conflicts
File.cp_r "samples", "tmp", fn(source, destination) ->
  IO.gets("Overwriting #{destination} by #{source}. Type y to confirm.") == "y"
end
Source
cp_r!(source, destination, callback \\ fn _, _ -> true end)

The same as cp_r/3, but raises File.CopyError if it fails. Returns the list of copied files otherwise.

Source
cwd()

Gets the current working directory. In rare circumstances, this function can fail on Unix. It may happen if read permission does not exist for the parent directories of the current directory. For this reason, returns { :ok, cwd } in case of success, { :error, reason } otherwise.

Source
cwd!()

The same as cwd/0, but raises an exception if it fails.

Source
dir?(path)

Returns true if the path is a directory.

Source
exists?(path)

Returns true if the given path exists. It can be regular file, directory, socket, symbolic link, named pipe or device file.

Examples

File.exists?("test/")
#=> true

File.exists?("missing.txt")
#=> false

File.exists?("/dev/null")
#=> true
Source
ls(path \\ ".")

Returns list of files in the given directory.

It returns { :ok, [files] } in case of success, { :error, reason } otherwise.

Source
ls!(dir \\ ".")

The same as ls/1 but raises File.Error in case of an error.

Source
mkdir(path)

Tries to create the directory path. Missing parent directories are not created. Returns :ok if successful, or {:error, reason} if an error occurs.

Typical error reasons are:

  • :eacces - Missing search or write permissions for the parent directories of path.
  • :eexist - There is already a file or directory named path.
  • :enoent - A component of path does not exist.
  • :enospc - There is a no space left on the device.
  • :enotdir - A component of path is not a directory On some platforms, :enoent is returned instead.
Source
mkdir!(path)

Same as mkdir/1, but raises an exception in case of failure. Otherwise :ok.

Source
mkdir_p(path)

Tries to create the directory path. Missing parent directories are created. Returns :ok if successful, or {:error, reason} if an error occurs.

Typical error reasons are:

  • :eacces - Missing search or write permissions for the parent directories of path.
  • :enospc - There is a no space left on the device.
  • :enotdir - A component of path is not a directory.
Source
mkdir_p!(path)

Same as mkdir_p/1, but raises an exception in case of failure. Otherwise :ok.

Source
open(path, modes \\ [])

Opens the given path according to the given list of modes.

In order to write and read files, one must use the functions in the IO module. By default, a file is opened in binary mode which requires the functions IO.binread/2 and IO.binwrite/2 to interact with the file. A developer may pass :utf8 as an option when opening the file and then all other functions from IO are available, since they work directly with Unicode data.

The allowed modes:

  • :read - The file, which must exist, is opened for reading.

  • :write - The file is opened for writing. It is created if it does not exist. If the file exists, and if write is not combined with read, the file will be truncated.

  • :append - The file will be opened for writing, and it will be created if it does not exist. Every write operation to a file opened with append will take place at the end of the file.

  • :exclusive - The file, when opened for writing, is created if it does not exist. If the file exists, open will return { :error, :eexist }.

  • :charlist - When this term is given, read operations on the file will return char lists rather than binaries;

  • :compressed - Makes it possible to read or write gzip compressed files. The compressed option must be combined with either read or write, but not both. Note that the file size obtained with stat/1 will most probably not match the number of bytes that can be read from a compressed file.

  • :utf8 - This option denotes how data is actually stored in the disk file and makes the file perform automatic translation of characters to and from utf-8. If data is sent to a file in a format that cannot be converted to the utf-8 or if data is read by a function that returns data in a format that cannot cope with the character range of the data, an error occurs and the file will be closed.

If a function is given two modes (instead of a list), it dispatches to open/3.

Check http:\www.erlang.org/doc/man/file.html#open-2 for more information about other options like read_ahead and delayed_write.

This function returns:

  • { :ok, io_device } - The file has been opened in the requested mode. io_device is actually the pid of the process which handles the file. This process is linked to the process which originally opened the file. If any process to which the io_device is linked terminates, the file will be closed and the process itself will be terminated. An io_device returned from this call can be used as an argument to the IO module functions.

  • { :error, reason } - The file could not be opened.

Examples

{ :ok, file } = File.open("foo.tar.gz", [:read, :compressed])
IO.read(file, :line)
File.close(file)
Source
open(path, modes, function)

Similar to open/2 but expects a function as last argument.

The file is opened, given to the function as argument and automatically closed after the function returns, regardless if there was an error or not.

It returns { :ok, function_result } in case of success, { :error, reason } otherwise.

Do not use this function with :delayed_write option since automatically closing the file may fail (as writes are delayed).

Examples

File.open("file.txt", [:read, :write], fn(file) ->
  IO.read(file, :line)
end)
Source
open!(path, modes \\ [])

Same as open/2 but raises an error if file could not be opened. Returns the io_device otherwise.

Source
open!(path, modes, function)

Same as open/3 but raises an error if file could not be opened. Returns the function result otherwise.

Source
read(path)

Returns {:ok, binary}, where binary is a binary data object that contains the contents of path, or {:error, reason} if an error occurs.

Typical error reasons:

  • :enoent - The file does not exist.
  • :eacces - Missing permission for reading the file, or for searching one of the parent directories.
  • :eisdir - The named file is a directory.
  • :enotdir - A component of the file name is not a directory. On some platforms, :enoent is returned instead.
  • :enomem - There is not enough memory for the contents of the file.

You can use :file.format_error/1 to get a descriptive string of the error.

Source
read!(path)

Returns binary with the contents of the given filename or raises File.Error if an error occurs.

Source
regular?(path)

Returns true if the path is a regular file.

Examples

File.regular? __ENV__.file #=> true
Source
rm(path)

Tries to delete the file path. Returns :ok if successful, or {:error, reason} if an error occurs.

Typical error reasons are:

  • :enoent - The file does not exist.
  • :eacces - Missing permission for the file or one of its parents.
  • :eperm - The file is a directory and user is not super-user.
  • :enotdir - A component of the file name is not a directory. On some platforms, enoent is returned instead.
  • :einval - Filename had an improper type, such as tuple.

Examples

File.rm('file.txt')
#=> :ok

File.rm('tmp_dir/')
#=> {:error, :eperm}
Source
rm!(path)

Same as rm/1, but raises an exception in case of failure. Otherwise :ok.

Source
rm_rf(path)

Remove files and directories recursively at the given path. Symlinks are not followed but simply removed, non-existing files are simply ignored (i.e. doesn't make this function fail).

Returns { :ok, files_and_directories } with all files and directories removed in no specific order, { :error, reason, file } otherwise.

Examples

File.rm_rf "samples"
#=> { :ok, ["samples", "samples/1.txt"] }

File.rm_rf "unknown"
#=> { :ok, [] }
Source
rm_rf!(path)

Same as rm_rf/1 but raises File.Error in case of failures, otherwise the list of files or directories removed.

Source
rmdir(path)

Tries to delete the dir at path. Returns :ok if successful, or {:error, reason} if an error occurs.

Examples

File.rmdir('tmp_dir')
#=> :ok

File.rmdir('file.txt')
#=> {:error, :enotdir}
Source
rmdir!(path)

Same as rmdir/1, but raises an exception in case of failure. Otherwise :ok.

Source
stat(path, opts \\ [])

Returns information about the path. If it exists, it returns a { :ok, info } tuple, where info is a File.Info record. Retuns { :error, reason } with the same reasons as read/1 if a failure occurs.

Options

The accepted options are:

  • :time if the time should be :local, :universal or :posix. Default is :local.
Source
stat!(path, opts \\ [])

Same as stat/2 but returns the File.Stat directly and throws File.Error if an error is returned.

Source
stream!(path, modes \\ [], line_or_bytes \\ :line)

Opens the file at the given path with the given modes and returns a stream for each :line (default) or for a given number of bytes given by line_or_bytes.

The returned stream will fail for the same reasons as File.open!/2. Note that the file is opened only and every time streaming begins.

Note that stream by default uses IO.binread/2 unless the file is opened with an encoding, then the slower IO.read/2 is used to do the proper data conversion and guarantees.

Source
stream_to!(stream, path, modes \\ [])

Receives a stream and returns a new stream that will open the file at the given path for write with the extra modes and write each value to the file.

The returned stream will fail for the same reasons as File.open!/2. Note that the file is opened only and every time streaming begins.

Note that stream by default uses IO.binwrite/2 unless the file is opened with an encoding, then the slower IO.write/2 is used to do the proper data conversion and guarantees.

Source
touch(path, time \\ :calendar.local_time())

Updates modification time (mtime) and access time (atime) of the given file. File is created if it doesn’t exist.

Source
touch!(path, time \\ :calendar.local_time())

Same as touch/2 but raises an exception if it fails. Returns :ok otherwise.

Source
write(path, content, modes \\ [])

Writes content to the file path. The file is created if it does not exist. If it exists, the previous contents are overwritten. Returns :ok if successful, or {:error, reason} if an error occurs.

Typical error reasons are:

  • :enoent - A component of the file name does not exist.
  • :enotdir - A component of the file name is not a directory. On some platforms, enoent is returned instead.
  • :enospc - There is a no space left on the device.
  • :eacces - Missing permission for writing the file or searching one of the parent directories.
  • :eisdir - The named file is a directory.

Check File.open/2 for existing modes.

Source
write!(path, content, modes \\ [])

Same as write/3 but raises an exception if it fails, returns :ok otherwise.

Source
write_stat(path, stat, opts \\ [])

Writes the given File.Stat back to the filesystem at the given path. Returns :ok or { :error, reason }.

Source
write_stat!(path, stat, opts \\ [])

Same as write_stat/3 but raises an exception if it fails. Returns :ok otherwise.

Source