file(3erl)
π file(3erl) β Erlang Module Definition π
Okay bestie, welcome to file, the Erlang Manual Page that is literally the blueprint for talking to the file system. It's giving essential, it's giving foundational, and yes, it's giving "read every line because the details matter." π
πΈ NAME πΈ
file β File interface module. π
β¨ DESCRIPTION β¨
This module provides an interface to the file system. No cap.
β οΈ Warning β οΈ
Okay, real talk: file operations are only guaranteed to appear atomic when you go through the same file server. A NIF or another OS process may observe intermediate steps on certain operations on some operating systems β for example, renaming an existing file on Windows, or write_file_info/2 on any OS at the time of writing. So yeah, "atomic" has a whole vibe and a whole boundary. π«Ά
Regarding filename encoding, the Erlang VM can operate in two modes. The current mode can be queried using function native_name_encoding/0. It returns latin1 or utf8. β¨
In latin1 mode, the Erlang VM does not change the encoding of filenames. In utf8 mode, filenames can contain Unicode characters greater than 255, and the VM converts filenames back and forth to the native filename encoding (usually UTF-8, but UTF-16 on Windows). π
The default mode depends on the operating system. Windows, MacOS X and Android enforce consistent filename encoding and therefore the VM uses utf8 mode.
On operating systems with transparent naming (for example, all Unix systems except MacOS X), default is utf8 if the terminal supports UTF-8, otherwise latin1. The default can be overridden using +fnl (to force latin1 mode) or +fnu (to force utf8 mode) when starting erl. π»
On operating systems with transparent naming, files can be inconsistently named, for example, some files are encoded in UTF-8 while others are encoded in ISO Latin-1. The concept of raw filenames is introduced to handle file systems with inconsistent naming when running in utf8 mode.
A raw filename is a filename specified as a binary. The Erlang VM does not translate a filename specified as a binary on systems with transparent naming.
When running in utf8 mode, functions list_dir/1 and read_link/1 never return raw filenames. To return all filenames including raw filenames, use functions list_dir_all/1 and read_link_all/1. π¦
See also section Notes About Raw Filenames in the STDLIB User's Guide.
π Note π
File operations used to accept filenames containing null characters (integer value zero). This caused the name to be truncated and in some cases arguments to primitive operations to be mixed up. Filenames containing null characters inside the filename are now rejected and will cause primitive file operations to fail. π«
𧬠DATA TYPES π§¬
deep_list()
deep_list() = [char() | atom() | deep_list()]
A recursive list situation β yes, it can contain itself. Iconic. π
fd()
A file descriptor representing a file opened in raw mode. π
filename()
filename() = string()
See also the documentation of the name_all() type.
filename_all()
filename_all() = string() | binary()
See also the documentation of the name_all() type.
io_device()
io_device() = pid() | fd()
As returned by open/2; pid() is a process handling I/O-protocols.
name()
name() = string() | atom() | deep_list()
If VM is in Unicode filename mode, string() and char() are allowed to be > 255. See also the documentation of the name_all() type.
name_all()
name_all() =
string() | atom() | deep_list() | (RawFilename :: binary())
If VM is in Unicode filename mode, characters are allowed to be > 255. RawFilename is a filename not subject to Unicode translation, meaning that it can contain characters not conforming to the Unicode encoding expected from the file system (that is, non-UTF-8 characters although the VM is started in Unicode filename mode). Null characters (integer value zero) are not allowed in filenames (not even at the end). π₯
posix()
posix() =
eacces | eagain | ebadf | ebadmsg | ebusy | edeadlk |
edeadlock | edquot | eexist | efault | efbig | eftype |
eintr | einval | eio | eisdir | eloop | emfile | emlink |
emultihop | enametoolong | enfile | enobufs | enodev |
enolck | enolink | enoent | enomem | enospc | enosr | enostr |
enosys | enotblk | enotdir | enotsup | enxio | eopnotsupp |
eoverflow | eperm | epipe | erange | erofs | espipe | esrch |
estale | etxtbsy | exdev
An atom that is named from the POSIX error codes used in Unix, and in the runtime libraries of most C compilers. π
date_time()
date_time() = calendar:datetime()
Must denote a valid date and time.
file_info()
file_info() =
#file_info{size = integer() >= 0 | undefined,
type =
device | directory | other | regular |
symlink | undefined,
access =
read | write | read_write | none | undefined,
atime =
file:date_time() |
integer() >= 0 |
undefined,
mtime =
file:date_time() |
integer() >= 0 |
undefined,
ctime =
file:date_time() |
integer() >= 0 |
undefined,
mode = integer() >= 0 | undefined,
links = integer() >= 0 | undefined,
major_device = integer() >= 0 | undefined,
minor_device = integer() >= 0 | undefined,
inode = integer() >= 0 | undefined,
uid = integer() >= 0 | undefined,
gid = integer() >= 0 | undefined}
This is the big info record, loaded with all the metadata vibes. π
location()
location() =
integer() |
{bof, Offset :: integer()} |
{cur, Offset :: integer()} |
{eof, Offset :: integer()} |
bof | cur | eof
Where you at in the file? That's the location vibe. π
mode()
mode() =
read | write | append | exclusive | raw | binary |
{delayed_write,
Size :: integer() >= 0,
Delay :: integer() >= 0} |
delayed_write |
{read_ahead, Size :: integer() >= 1} |
read_ahead | compressed | compressed_one |
{encoding, unicode:encoding()} |
sync
file_info_option()
file_info_option() =
{time, local} | {time, universal} | {time, posix} | raw
π EXPORTS π
Every export gets its own little spotlight. Let's go. π
advise(IoDevice, Offset, Length, Advise) -> ok | {error, Reason}
Types:
IoDevice = io_device()
Offset = Length = integer()
Advise = posix_file_advise()
Reason = posix() | badarg
posix_file_advise() =
normal | sequential | random | no_reuse | will_need |
dont_need
advise/4 can be used to announce an intention to access file data in a specific pattern in the future, thus allowing the operating system to perform appropriate optimizations.
On some platforms, this function might have no effect. So don't be shocked if the OS just shrugs. π
allocate(File, Offset, Length) -> ok | {error, posix()}
Types:
File = io_device()
Offset = Length = integer() >= 0
allocate/3 can be used to preallocate space for a file.
This function only succeeds in platforms that provide this feature.
change_group(Filename, Gid) -> ok | {error, Reason}
Types:
Filename = name_all()
Gid = integer()
Reason = posix() | badarg
Changes group of a file. See write_file_info/2. π«Ά
change_mode(Filename, Mode) -> ok | {error, Reason}
Types:
Filename = name_all()
Mode = integer()
Reason = posix() | badarg
Changes permissions of a file. See write_file_info/2.
change_owner(Filename, Uid) -> ok | {error, Reason}
Types:
Filename = name_all()
Uid = integer()
Reason = posix() | badarg
Changes owner of a file. See write_file_info/2.
change_owner(Filename, Uid, Gid) -> ok | {error, Reason}
Types:
Filename = name_all()
Uid = Gid = integer()
Reason = posix() | badarg
Changes owner and group of a file. See write_file_info/2.
change_time(Filename, Mtime) -> ok | {error, Reason}
Types:
Filename = name_all()
Mtime = date_time()
Reason = posix() | badarg
Changes the modification and access times of a file. See write_file_info/2.
change_time(Filename, Atime, Mtime) -> ok | {error, Reason}
Types:
Filename = name_all()
Atime = Mtime = date_time()
Reason = posix() | badarg
Changes the modification and last access times of a file. See write_file_info/2.
close(IoDevice) -> ok | {error, Reason}
Types:
IoDevice = io_device()
Reason = posix() | badarg | terminated
Closes the file referenced by IoDevice. It mostly returns ok, except for some severe errors such as out of memory.
Notice that if option delayed_write was used when opening the file, close/1 can return an old write error and not even try to close the file. See open/2. π
consult(Filename) -> {ok, Terms} | {error, Reason}
Types:
Filename = name_all()
Terms = [term()]
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
Reads Erlang terms, separated by '.', from Filename. Returns one of the following:
{ok, Terms}: The file was successfully read. Slay.{error, atom()}: An error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}: An error occurred when interpreting the Erlang terms in the file. To convert the three-element tuple to an English description of the error, useformat_error/1.
Example:
f.txt: {person, "kalle", 25}.
{person, "pelle", 30}.
1> file:consult("f.txt").
{ok,[{person,"kalle",25},{person,"pelle",30}]}
The encoding of Filename can be set by a comment, as described in epp(3erl). π§
copy/2 & copy/3 β the copy twins π―
copy(Source, Destination) -> {ok, BytesCopied} | {error, Reason}
copy(Source, Destination, ByteCount) ->
{ok, BytesCopied} | {error, Reason}
Types:
Source = Destination = io_device() | Filename | {Filename,
Modes}
Filename = name_all()
Modes = [mode()]
ByteCount = integer() >= 0 | infinity
BytesCopied = integer() >= 0
Reason = posix() | badarg | terminated
Copies ByteCount bytes from Source to Destination. Source and Destination refer to either filenames or IO devices from, for example, open/2. ByteCount defaults to infinity, denoting an infinite number of bytes. So yes, infinity is the default β don't come for me. π
So like, Argument Modes is a list of possible modes (peep open/2 for the deets), and it defaults to []. β¨
If both Source and Destination are filenames, the files get opened with [read, binary] and [write, binary] prepended to their mode lists respectively β purely to optimize the copy, bestie. Speed demon behavior. π
If Source is a filename, it's opened with read mode prepended to the mode list before the copy, and closed when done. If Destination is a filename, same deal but with write mode prepended, and closed when done. Clean up after yourself, periodt. π
Returns {ok, BytesCopied}, where BytesCopied is the number of bytes that was copied β which can lowkey be less than ByteCount if end of file was encountered on the source. If the operation fails, {error, Reason} is returned.
Typical error reasons: as for open/2 if a file had to be opened, and as for read/2 and write/2. iykyk π¦
datasync(IoDevice) -> ok | {error, Reason}
Types:
IoDevice = io_device()Reason = posix() | badarg | terminated
Ensures that any buffers kept by the operating system (not by the Erlang runtime system, like, the OS is the one holding the bag here) are written to disk. In many ways it resembles fsync but it does not update some of the metadata of the file, such as the access time. On some platforms this function has no effect β literally just vibes, nothing happens. π
Apps that access databases or log files often write a tiny data fragment (for example, one line in a log file) and then call fsync() immediately to ensure that the written data is physically stored on the hard disk. Unfortunately, fsync() always initiates two write operations: one for the newly written data and another one to update the modification time stored in the inode. If the modification time is not a part of the transaction concept, fdatasync() can be used to avoid unnecessary inode disk write operations. Not me saving you a whole write π
Available only in some POSIX systems, this call results in a call to fsync(), or has no effect in systems not providing the fdatasync() syscall.
del_dir(Dir) -> ok | {error, Reason}
Types:
Dir = name_all()Reason = posix() | badarg
Tries to delete directory Dir. The directory must be empty before it can be deleted β no sneaky files hiding in there, it will not go. Returns ok if successful.
Typical error reasons:
eaccesβ Missing search or write permissions for the parent directories ofDir.eexistβ The directory is not empty. (the audacity π)enoentβ The directory does not exist.enotdirβ A component ofDiris not a directory. On some platforms,enoentis returned instead.einvalβ Attempt to delete the current directory. On some platforms,eaccesis returned instead.
del_dir_r(File) -> ok | {error, Reason}
Types:
File = name_all()Reason = posix() | badarg
Deletes file or directory File. If File is a directory, its contents is first recursively deleted β it goes all the way down, main character energy π. Returns:
okβ The operation completed without errors. slay.{error, posix()}β An error occurred when accessing or deletingFile. If some file or directory underFilecould not be deleted,Filecannot be deleted as it is non-empty, and{error, eexist}is returned. π«
delete(Filename) -> ok | {error, Reason}
delete(Filename, Opts) -> ok | {error, Reason}
Types:
Filename = name_all()Opts = [delete_option()]Reason = posix() | badargdelete_option() = raw
Tries to delete file Filename. Returns ok if successful.
If the option raw is set, the file server is not called. This can be useful in particular during the early boot stage when the file server is not yet registered, to still be able to delete local files. Genuinely iconic little escape hatch. π§
Typical error reasons:
enoentβ The file does not exist.eaccesβ Missing permission for the file or one of its parents.epermβ The file is a directory and the user is not superuser.enotdirβ A component of the filename is not a directory. On some platforms,enoentis returned instead.einvalβFilenamehas an improper type, such as tuple. (a tuple?? bestie no π)
Warning: In a future release, a bad type for argument Filename will probably generate an exception.
eval(Filename) -> ok | {error, Reason}
Types:
Filename = name_all()Reason = posix() | badarg | terminated | system_limit | {Line :: integer(), Mod :: module(), Term :: term()}
Reads and evaluates Erlang expressions, separated by '.' (or ',' β a sequence of expressions is also an expression) from Filename. The result of the evaluation is not returned; any expression sequence in the file must be there for its side effect. Like, it's doing stuff, not reporting back. Returns one of the following:
okβ The file was read and evaluated. π{error, atom()}β An error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}β An error occurred when interpreting the Erlang expressions in the file. To convert the three-element tuple to an English description of the error, useformat_error/1.
The encoding of Filename can be set by a comment, as described in epp(3erl).
eval(Filename, Bindings) -> ok | {error, Reason}
Types:
Filename = name_all()Bindings = erl_eval:binding_struct()Reason = posix() | badarg | terminated | system_limit | {Line :: integer(), Mod :: module(), Term :: term()}
The same as eval/1, but the variable bindings Bindings are used in the evaluation. For information about the variable bindings, see erl_eval(3erl). π¦
format_error(Reason) -> Chars
Types:
Reason = posix() | badarg | terminated | system_limit | {Line :: integer(), Mod :: module(), Term :: term()}Chars = string()
Given the error reason returned by any function in this module, returns a descriptive string of the error in English. It's your translator bestie fr fr π«Ά
get_cwd() -> {ok, Dir} | {error, Reason}
Types:
Dir = filename()Reason = posix()
Returns {ok, Dir}, where Dir is the current working directory of the file server. Where are we? Mystery solved. πΈ
Note: In rare circumstances, this function can fail on Unix. It can occur if read permission does not exist for the parent directories of the current directory.
A typical error reason:
eaccesβ Missing read permission for one of the parents of the current directory.
get_cwd(Drive) -> {ok, Dir} | {error, Reason}
Types:
Drive = string()Dir = filename()Reason = posix() | badarg
Returns {ok, Dir} or {error, Reason}, where Dir is the current working directory of the specified drive.
Drive is to be of the form "Letter:", for example, "c:". (yes with the colon, don't forget it π
)
Returns {error, enotsup} on platforms that have no concept of current drive (Unix, for example). Unix said "drives? never heard of her." π
Typical error reasons:
enotsupβ The operating system has no concept of drives.eaccesβ The drive does not exist.einvalβ The format ofDriveis invalid.
list_dir(Dir) -> {ok, Filenames} | {error, Reason}
Types:
Dir = name_all()Filenames = [filename()]Reason = posix() | badarg | {no_translation, Filename :: unicode:latin1_binary()}
Lists all files in a directory, except files with raw filenames. Returns {ok, Filenames} if successful, otherwise {error, Reason}. Filenames is a list of the names of all the files in the directory. The names are not sorted β so don't come for her about ordering, she's not doing that π₯
Typical error reasons:
eaccesβ Missing search or write permissions forDiror one of its parent directories.enoentβ The directory does not exist.{no_translation, Filename}βFilenameis abinary()with characters coded in ISO Latin-1 and the VM was started with parameter+fnue.
list_dir_all(Dir) -> {ok, Filenames} | {error, Reason}
Types:
Dir = name_all()Filenames = [filename_all()]Reason = posix() | badarg
Lists all the files in a directory, including files with raw filenames β the deluxe version, nobody left out. π Returns {ok, Filenames} if successful, otherwise {error, Reason}. Filenames is a list of the names of all the files in the directory. The names are not sorted (same as above, we don't do that here).
Typical error reasons:
eaccesβ Missing search or write permissions forDiror one of its parent directories.enoentβ The directory does not exist.
make_dir(Dir) -> ok | {error, Reason}
Types:
Dir = name_all()Reason = posix() | badarg
Tries to create directory Dir. Missing parent directories are not created β she only makes the one dir you asked for, no free extras. Returns ok if successful.
Typical error reasons:
eaccesβ Missing search or write permissions for the parent directories ofDir.eexistβ A file or directory namedDirexists already.enoentβ A component ofDirdoes not exist.enospcβ No space is left on the device. πenotdirβ A component ofDiris not a directory. On some platforms,enoentis returned instead.
make_link(Existing, New) -> ok | {error, Reason}
Types:
Existing = New = name_all()Reason = posix() | badarg
Okay so this call makes a hard link from Existing to New on platforms supporting links (Unix and Windows). It returns ok if the link was successfully created, otherwise {error, Reason}. On platforms not supporting links, {error,enotsup} is returned. π
Typical error reasons:
eaccesβ Missing read or write permissions for the parent directories ofExistingorNew.eexistβNewalready exists.enotsupβ Hard links are not supported on this platform.
πΈ make_symlink(Existing, New) -> ok | {error, Reason}
Types:
Existing = New = name_all()
Reason = posix() | badarg
Creates a symbolic link New to the file or directory Existing on platforms supporting symbolic links (most Unix systems and Windows, beginning with Vista). Existing does not need to exist. Returns ok if the link is successfully created, otherwise {error, Reason}. On platforms not supporting symbolic links, {error, enotsup} is returned. π¦
Typical error reasons:
eaccesβ Missing read or write permissions for the parent directories ofExistingorNew.eexistβNewalready exists.enotsupβ Symbolic links are not supported on this platform.epermβ User does not have privileges to create symbolic links (SeCreateSymbolicLinkPrivilegeon Windows).
π native_name_encoding() -> latin1 | utf8
Returns the filename encoding mode. If it is latin1, the system translates no filenames. If it is utf8, filenames are converted back and forth to the native filename encoding (usually UTF-8, but UTF-16 on Windows).
π open(File, Modes) -> {ok, IoDevice} | {error, Reason}
Types:
File = Filename | iodata()
Filename = name_all()
Modes = [mode() | ram | directory]
IoDevice = io_device()
Reason = posix() | badarg | system_limit
Opens file File in the mode determined by Modes, which can contain one or more of the following options:
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 andwriteis not combined withread, the file is truncated.appendβ The file is opened for writing. It is created if it does not exist. Every write operation to a file opened withappendtakes place at the end of the file.exclusiveβ The file is opened for writing. It is created if it does not exist. If the file exists,{error, eexist}is returned.
β οΈ Warning: This option does not guarantee exclusiveness on file systems not supportingO_EXCLproperly, such asNFS. Do not depend on this option unless you know that the file system supports it (in general, local file systems are safe).
rawβ Allows faster access to a file, as no Erlang process is needed to handle the file. However, a file opened in this way has the following limitations:- The functions in the
iomodule cannot be used, as they can only talk to an Erlang process. Instead, use functionsread/2,read_line/1, andwrite/2. - Especially if
read_line/1is to be used on a raw file, it is recommended to combine this option with option{read_ahead, Size}as line-oriented I/O is inefficient without buffering. - Only the Erlang process that opened the file can use it.
- A remote Erlang file server cannot be used. The computer on which the Erlang node is running must have access to the file system (directly or through NFS).
- The functions in the
binaryβ Read operations on the file return binaries rather than lists.{delayed_write, Size, Delay}β Data in subsequentwrite/2calls is buffered until at leastSizebytes are buffered, or until the oldest buffered data isDelaymilliseconds old. Then all buffered data is written in one operating system call. The buffered data is also flushed before some other file operation thanwrite/2is executed.- The purpose of this option is to increase performance by reducing the number of operating system calls. Thus, the
write/2calls must be for sizes significantly less thanSize, and not interspersed by too many other file operations. - When this option is used, the result of
write/2calls can prematurely be reported as successful, and if a write error occurs, the error is reported as the result of the next file operation, which is not executed. - For example, when
delayed_writeis used, after a number ofwrite/2calls,close/1can return{error, enospc}, as there is not enough space on the disc for previously written data.close/1must probably be called again, as the file is still open.
- The purpose of this option is to increase performance by reducing the number of operating system calls. Thus, the
delayed_writeβ The same as{delayed_write, Size, Delay}with reasonable default values forSizeandDelay(roughly some 64 KB, 2 seconds).{read_ahead, Size}β Activates read data buffering. Ifread/2calls are for significantly less thanSizebytes, read operations to the operating system are still performed for blocks ofSizebytes. The extra data is buffered and returned in subsequentread/2calls, giving a performance gain as the number of operating system calls is reduced. Theread_aheadbuffer is also highly used by functionread_line/1in raw mode, therefore this option is recommended (for performance reasons) when accessing raw files using that function. Ifread/2calls are for sizes not significantly less than, or even greater thanSizebytes, no performance gain can be expected.read_aheadβ The same as{read_ahead, Size}with a reasonable default value forSize(roughly some 64 KB).compressedβ Makes it possible to read or write gzip compressed files. Optioncompressedmust be combined withreadorwrite, but not both. Notice that the file size obtained withread_file_info/1does probably not match the number of bytes that can be read from a compressed file.compressed_oneβ Read one member of a gzip compressed file. Optioncompressed_onecan only be combined withread.{encoding, Encoding}β Makes the file perform automatic translation of characters to and from a specific (Unicode) encoding. Notice that the data supplied towrite/2or returned byread/2still is byte-oriented; this option denotes only how data is stored in the disk file.
Depending on the encoding, different methods of reading and writing data is preferred. The default encoding of latin1 implies using this module (file) for reading and writing data as the interfaces provided here work with byte-oriented data. Using other (Unicode) encodings makes the io(3erl) functions get_chars, get_line, and put_chars more suitable, as they can work with the full Unicode range.
If data is sent to an io_device() in a format that cannot be converted to the specified encoding, 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 is closed.
Allowed values for Encoding:
latin1β The default encoding. Bytes supplied to the file, that is,write/2are written "as is" on the file. Likewise, bytes read from the file, that is,read/2are returned "as is". If moduleio(3erl)is used for writing, the file can only cope with Unicode characters up to code point255(the ISO Latin-1 range).unicodeorutf8β Characters are translated to and from UTF-8 encoding before they are written to or read from the file. A file opened in this way can be readable using functionread/2, as long as no data stored on the file lies beyond the ISO Latin-1 range (0..255), but failure occurs if the data contains Unicode code points beyond that range. The file is best read with the functions in the Unicode aware moduleio(3erl). Bytes written to the file by any means are translated to UTF-8 encoding before being stored on the disk file.utf16or{utf16,big}β Works likeunicode, but translation is done to and from big endian UTF-16 instead of UTF-8.{utf16,little}β Works likeunicode, but translation is done to and from little endian UTF-16 instead of UTF-8.utf32or{utf32,big}β Works likeunicode, but translation is done to and from big endian UTF-32 instead of UTF-8.{utf32,little}β Works likeunicode, but translation is done to and from little endian UTF-32 instead of UTF-8.
The Encoding can be changed for a file "on the fly" by using function io:setopts/2. So a file can be analyzed in latin1 encoding for, for example, a BOM, positioned beyond the BOM and then be set for the right encoding before further reading. For functions identifying BOMs, see module unicode(3erl).
This option is not allowed on raw files.
ramβFilemust beiodata(). Returns anfd(), which lets modulefileoperate on the data in-memory as if it is a file. π«Άsyncβ on platforms that support it, this flips on the POSIXO_SYNCsynchronous I/O flag, or whatever the platform's version of that is (hiFILE_FLAG_WRITE_THROUGHon Windows π) so that writes to the file block until the data is physically written to disk. But bestie, hear me: the exact semantics of this flag differ from platform to platform π like, neither Linux nor Windows actually guarantees that all file metadata is written before the call returns. For the precise tea, go read your platform's own docs. And on platforms with no support for POSIXO_SYNCor equivalent, using thesyncflag makesopenreturn{error, enotsup}.directoryβ letsopenwork on directories. That's it, that's the whole vibe ποΈ
β¨ Returns
{ok, IoDevice}β the file is opened in the requested mode, andIoDeviceis a reference to the file π{error, Reason}β the file cannot be opened π
IoDevice is really the pid of the process that handles the file. That process monitors the process that originally opened the file (the owner process). If the owner process terminates, the file is closed and the process itself terminates too. An IoDevice returned from this call can be used as an argument to the I/O functions (see io(3erl)).
β οΈ Warning β okay so this function can open any file, but we recommend against using it for NFS-mounted files, FIFOs, devices, or anything similar, because they can cause IO threads to hang forever ππ If your application needs to interact with these kinds of files, we recommend breaking those parts out into a port program instead.
π Note β in previous versions offile, modes were specified as one of the atomsread,write, orread_writeinstead of a list. That's still allowed for backwards-compatibility reasons, but do not use it for new code, bestie. Also note thatread_writeis not allowed in a mode list. π«
Typical error reasons, since you asked:
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 filename is not a directory, or the filename itself is not a directory if directory mode was specified. On some platforms,enoentis returned instead. rude.enospcβ there is no space left on the device (if write access was specified).
πΈ path_consult(Path, Filename) -> {ok, Terms, FullName} | {error, Reason}
Types:
Path = [Dir]
Dir = Filename = name_all()
Terms = [term()]
FullName = filename_all()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute filename, Path is ignored, periodt. Then it reads Erlang terms, separated by ., from the file π
Returns one of the following:
{ok, Terms, FullName}β the file is successfully read.FullNameis the full name of the file.{error, enoent}β the file cannot be found in any of the directories inPath. π{error, atom()}β an error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}β an error occurred when interpreting the Erlang terms in the file. Useformat_error/1to convert the three-element tuple into an English description of the error. very helpful of it ngl π«Ά
The encoding of Filename can be set by a comment as described in epp(3erl).
π¦ path_eval(Path, Filename) -> {ok, FullName} | {error, Reason}
Types:
Path = [Dir :: name_all()]
Filename = name_all()
FullName = filename_all()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute filename, Path is ignored. Then it reads and evaluates Erlang expressions, separated by . (or , β a sequence of expressions is also an expression, iconique), from the file. The result of the evaluation is not returned; any expression sequence in the file has to be there for its side effect only β¨
Returns one of the following:
{ok, FullName}β the file is read and evaluated.FullNameis the full name of the file.{error, enoent}β the file cannot be found in any of the directories inPath.{error, atom()}β an error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}β an error occurred when interpreting the Erlang expressions in the file. Useformat_error/1to convert the three-element tuple into an English description of the error.
The encoding of Filename can be set by a comment as described in epp(3erl).
π path_open(Path, Filename, Modes) -> {ok, IoDevice, FullName} | {error, Reason}
Types:
Path = [Dir :: name_all()]
Filename = name_all()
Modes = [mode() | directory]
IoDevice = io_device()
FullName = filename_all()
Reason = posix() | badarg | system_limit
Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute filename, Path is ignored. Then it opens the file in the mode determined by Modes π
Returns one of the following:
{ok, IoDevice, FullName}β the file is opened in the requested mode.IoDeviceis a reference to the file, andFullNameis the full name of the file. two-for-one slay π{error, enoent}β the file cannot be found in any of the directories inPath.{error, atom()}β the file cannot be opened.
π path_script(Path, Filename) -> {ok, Value, FullName} | {error, Reason}
Types:
Path = [Dir :: name_all()]
Filename = name_all()
Value = term()
FullName = filename_all()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute filename, Path is ignored. Then it reads and evaluates Erlang expressions, separated by . (or , β a sequence of expressions is also an expression), from the file.
Returns one of the following:
{ok, Value, FullName}β the file is read and evaluated.FullNameis the full name of the file andValueis the value of the last expression. π{error, enoent}β the file cannot be found in any of the directories inPath.{error, atom()}β an error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}β an error occurred when interpreting the Erlang expressions in the file. Useformat_error/1to convert the three-element tuple into an English description of the error.
The encoding of Filename can be set by a comment as described in epp(3erl).
π path_script(Path, Filename, Bindings) -> {ok, Value, FullName} | {error, Reason}
Types:
Path = [Dir :: name_all()]
Filename = name_all()
Bindings = erl_eval:binding_struct()
Value = term()
FullName = filename_all()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
The same as path_script/2 but the variable bindings Bindings are used in the evaluation. See erl_eval(3erl) about variable bindings π§ β¨
π₯ pid2name(Pid) -> {ok, Filename} | undefined
Types:
Filename = filename_all()
Pid = pid()
If Pid is an I/O device β that is, a pid returned from open/2 β this function returns the filename, or rather:
{ok, Filename}β if the file server of this node is not a slave, the file was opened by the file server of this node (this implies thatPidmust be a local pid) and the file is not closed.Filenameis the filename in flat string format. π§Ύundefinedβ in all other cases. sorry bestie, no name for you π
β οΈ Warning β this function is intended for debugging only. like, it's giving "just here to help you snoop", not "production main character" π
β position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason}
Types:
IoDevice = io_device()
Location = location()
NewPosition = integer()
Reason = posix() | badarg | terminated
Sets the position of the file referenced by IoDevice to Location. Returns {ok, NewPosition} (as an absolute offset) if it worked, otherwise {error, Reason}. Location is one of the following:
Offsetβ the same as{bof, Offset}.{bof, Offset}β absolute offset.{cur, Offset}β offset from the current position.{eof, Offset}β offset from the end of file.bof|cur|eofβ the same as above withOffset0. π―
Okay so β π
offsets are counted in bytes, not characters. If the file was opened with some encoding other than latin1, one byte does not equal one character. So positioning in a file like that can only be done to known character boundaries β meaning: a position you grabbed earlier by getting the current position, the beginning/end of the file, or some other position you know is on a correct character boundary by some other means (typically beyond a byte order mark in the file, which has a known byte-size). π
A typical error reason here is:
einvalβ either Location is illegal, or it evaluates to a negative offset in the file. Heads up: if the resulting position is a negative value, the result is an error, and after the call the file position is undefined. π
β¨ pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason} β¨
Types:
IoDevice = io_device()
LocNums =
[{Location :: location(), Number :: integer() >= 0}]
DataL = [Data]
Data = string() | binary() | eof
Reason = posix() | badarg | terminated
Does a whole sequence of pread/3 calls in one operation, which is way more efficient than calling them one at a time. Returns {ok, [Data, ...]} or {error, Reason}, where each Data β the result of the corresponding pread β is either a list or a binary depending on the mode of the file, or eof if the requested position is beyond end of file. π¦
Since the position is specified as a byte-offset, take special caution when you're working with files where encoding is set to something other than latin1, because not every byte position is a valid character boundary on such a file. π
β¨ pread(IoDevice, Location, Number) -> {ok, Data} | eof | {error, Reason} β¨
Types:
IoDevice = io_device()
Location = location()
Number = integer() >= 0
Data = string() | binary()
Reason = posix() | badarg | terminated
Combines position/2 and read/2 into one operation, which is more efficient than calling them one at a time. slay β¨
Location is only allowed to be an integer for raw and ram modes.
The current position of the file after the operation is undefined for raw mode and unchanged for ram mode. π«Ά
Since the position is specified as a byte-offset, take special caution when working with files where encoding is set to something other than latin1, because not every byte position is a valid character boundary on such a file.
β¨ pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}} β¨
Types:
IoDevice = io_device()
LocBytes = [{Location :: location(), Bytes :: iodata()}]
N = integer() >= 0
Reason = posix() | badarg | terminated
Does a whole sequence of pwrite/3 calls in one operation, which is more efficient than calling them one at a time. Returns ok or {error, {N, Reason}}, where N is the number of successful writes done before the failure. π
When you're positioning in a file with an encoding other than latin1, caution must be taken to set the position on a correct character boundary. For details, see position/2.
β¨ pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason} β¨
Types:
IoDevice = io_device()
Location = location()
Bytes = iodata()
Reason = posix() | badarg | terminated
Combines position/2 and write/2 in one operation, which is more efficient than calling them one at a time. π
Location is only allowed to be an integer for raw and ram modes.
The current position of the file after the operation is undefined for raw mode and unchanged for ram mode.
When positioning in a file with an encoding other than latin1, caution must be taken to set the position on a correct character boundary. For details, see position/2.
β¨ read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason} β¨
Types:
IoDevice = io_device() | atom()
Number = integer() >= 0
Data = string() | binary()
Reason =
posix() |
badarg | terminated |
{no_translation, unicode, latin1}
Reads Number bytes/characters from the file referenced by IoDevice. Bestie, listen β the functions read/2, pread/3, and read_line/1 are the only ways to read from a file opened in raw mode (although they work for normally opened files too, no cap). π
For files where encoding is set to something other than latin1, one character can be represented by more than one byte on the file. The parameter Number always denotes the number of characters read from the file, while the position in the file can move much further than this number when you're reading a Unicode file. π§
Also, if encoding is set to something other than latin1, the read/3 call fails if the data contains characters larger than 255 β which is exactly why module io(3erl) is to be preferred when reading such a file.
The function returns:
{ok, Data}β if the file was opened in binary mode, the read bytes come back in a binary, otherwise in a list. The list or binary is shorter than the number of bytes requested if end of file was reached.eofβ returned ifNumber>0and end of file was reached before anything at all could be read.{error, Reason}β an error occurred. π
Typical error reasons:
ebadfβ the file is not opened for reading.{no_translation, unicode, latin1}β the file is opened with another encoding thanlatin1and the data in the file cannot be translated to the byte-oriented data that this function returns.
β¨ read_file(Filename) -> {ok, Binary} | {error, Reason} β¨
Types:
Filename = name_all()
Binary = binary()
Reason = posix() | badarg | terminated | system_limit
Returns {ok, Binary}, where Binary is a binary data object containing the contents of Filename β 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 filename is not a directory. On some platforms,enoentis returned instead.enomemβ there is not enough memory for the contents of the file.
β¨ read_file_info(File) -> {ok, FileInfo} | {error, Reason} β¨
β¨ read_file_info(File, Opts) -> {ok, FileInfo} | {error, Reason} β¨
Types:
File = name_all() | io_device()
Opts = [file_info_option()]
FileInfo = file_info()
Reason = posix() | badarg
Grabs info about a file. Returns {ok, FileInfo} if it works out, otherwise {error, Reason}. FileInfo is a record file_info, defined in the Kernel include file file.hrl. Drop this directive into the module you're calling the function from: π
-include_lib("kernel/include/file.hrl").
The time type returned in atime, mtime, and ctime depends on the time type set in Opts :: {time, Type}, like this:
localβ returns local time.universalβ returns universal time.posixβ returns seconds since or before Unix time epoch, which is1970-01-01 00:00 UTC.
Default is {time, local}.
If the option raw is set, the file server is not called and only information about local files is returned. Note that this will break this module's atomicity guarantees, because it can race with a concurrent call to write_file_info/1,2. π
This option has no effect when the function is given an I/O device instead of a file name. Use open/2 with the raw mode to obtain a file descriptor first.
Note: as file times are stored in POSIX time on most OS, it is faster to query file information with option posix. β
The record file_info contains the following fields:
size=integer() >= 0β size of file in bytes.type=device | directory | other | regularβ the type of the file. Can also containsymlinkwhen returned fromread_link_info/1,2.access=read | write | read_write | noneβ the current system access to the file.atime=date_time() | integer() >= 0β the last time the file was read.mtime=date_time() | integer() >= 0β the last time the file was written.ctime=date_time() | integer() >=0β the interpretation of this time field depends on the operating system. On Unix, it is the last time the file or the inode was changed. In Windows, it is the create time.mode=integer() >= 0β the file permissions as the sum of the following bit values:8#00400β read permission: owner8#00200β write permission: owner8#00100β execute permission: owner8#00040β read permission: group8#00020β write permission: group8#00010β execute permission: group8#00004β read permission: other8#00002β write permission: other8#00001β execute permission: other16#800β set user id on execution16#400β set group id on execution
On Unix platforms, other bits than those listed above may be set. π
links=integer() >= 0β number of links to the file (this is always1for file systems that have no concept of links).major_device = integer() >= 0β tells you which file system the file is chillin' on. On Windows the number is literally the drive:0meansA:,1meansB:, and so on down the alphabet πminor_device = integer() >= 0β only actually valid for character devices on Unix. Everywhere else? It's just0, a whole lotta nothing π«inode = integer() >= 0β the inode number, iconic Unix behavior. On non-Unix file systems this is0.uid = integer() >= 0β who owns the file. On non-Unix file systems,0.gid = integer() >= 0β the group the file's owner rolls with. On non-Unix file systems,0.
Typical error reasons: π₯
eaccesβ you're missing search permission for one of the parent directories of the file. rude.enoentβ the file literally does not exist. gone. never was.enotdirβ a component of the filename is not a directory. ngl on some platforms you'll getenoentinstead, so don't @ me π
read_line(IoDevice) -> {ok, Data} | eof | {error, Reason}
Types:
IoDevice = io_device() | atom()
Data = string() | binary()
Reason =
posix() |
badarg | terminated |
{no_translation, unicode, latin1}
Okay so this one reads a line of bytes/characters from the file that IoDevice points at π Lines are delimited by the linefeed (LF, \n) character β but bestie, any carriage return (CR, \r) followed by a newline also counts as a single LF character (the carriage return gets silently ignored, so sneaky). The line comes back including the LF, but excluding any CR that was immediately followed by an LF. This is consistent with how io:get_line/2 behaves, so no cap there π«Ά If you hit end of file without any LF closing out the last line, you get a line with no trailing LF. generous queen.
You can use this on files opened in raw mode, but it's inefficient on raw files if the file wasn't opened with the option {read_ahead, Size} specified. So: combining raw and {read_ahead, Size} is highly recommended when you're opening a text file for raw line-oriented reading. do it for yourself π
If encoding is set to anything other than latin1, the read_line/1 call fails if the data contains characters larger than 255 β which is why module io(3erl) is to be preferred when reading a file like that.
The function returns:
{ok, Data}β one line from the file, including the trailing LF, but with CRLF sequences replaced by a single LF (see above π). If the file is opened in binary mode, the read bytes come back in a binary; otherwise in a list.eofβ returned if end of file was reached before anything at all could be read. not one single byte π{error, Reason}β an error occurred.
Typical error reasons: π₯
ebadfβ the file is not opened for reading. like, why are you even here.{no_translation, unicode, latin1}β the file is opened with another encoding thanlatin1and the data on the file cannot be translated to the byte-oriented data that this function returns.
read_link(Name) -> {ok, Filename} | {error, Reason}
Types:
Name = name_all()
Filename = filename()
Reason = posix() | badarg
Returns {ok, Filename} if Name refers to a symbolic link that is not a raw filename, otherwise {error, Reason}. On platforms that don't support symbolic links, the return value is {error,enotsup} β them's the breaks π¦
Typical error reasons: π₯
einvalβNamedoes not refer to a symbolic link, or the name of the file it refers to does not conform to the expected encoding.enoentβ the file does not exist.enotsupβ symbolic links are not supported on this platform. tragic.
read_link_all(Name) -> {ok, Filename} | {error, Reason}
Types:
Name = name_all()
Filename = filename_all()
Reason = posix() | badarg
Returns {ok, Filename} if Name refers to a symbolic link, or {error, Reason} otherwise. And yeah β on platforms that don't support symbolic links, the return value is {error,enotsup}.
β οΈ Notice that Filename can be either a list or a binary. so check your types before you start matching, bestie π
Typical error reasons: π₯
einvalβNamedoes not refer to a symbolic link.enoentβ the file does not exist.enotsupβ symbolic links are not supported on this platform.
read_link_info(Name) -> {ok, FileInfo} | {error, Reason}
read_link_info(Name, Opts) -> {ok, FileInfo} | {error, Reason}
Types:
Name = name_all()
Opts = [file_info_option()]
FileInfo = file_info()
Reason = posix() | badarg
Works exactly like read_file_info/1,2 β except that if Name is a symbolic link, you get info about the link itself in the file_info record, and the type field of that record is set to symlink. it's giving "don't look behind the curtain" π§
If the option raw is set, the file server is not called and only information about local files comes back. β οΈ But heads up: this breaks this module's atomicity guarantees, because it can race with a concurrent call to write_file_info/1,2. you've been warned, no cap.
If Name is not a symbolic link, this function returns the same result as read_file_info/1. And on platforms that don't support symbolic links, this function is always equivalent to read_file_info/1 β same energy, zero drama π
rename(Source, Destination) -> ok | {error, Reason}
Types:
Source = Destination = name_all()
Reason = posix() | badarg
Tries to rename the file Source to Destination. Yes, you can use it to move files (and directories) between directories β but it is not sufficient to specify the destination only. The destination filename must also be specified, babe. For example, if bar is a normal file and foo and baz are directories, rename("foo/bar", "baz") returns an error, but rename("foo/bar", "baz/bar") succeeds β¨ Returns ok if it's successful.
Note: Renaming of open files is not allowed on most platforms (see eacces below). so close it first, bestie π«Ά
Typical error reasons: π₯
eaccesβ missing read or write permissions for the parent directories ofSourceorDestination. On some platforms, this error is given if eitherSourceorDestinationis open.eexistβDestinationis not an empty directory. On some platforms, also given whenSourceandDestinationare not of the same type.einvalβSourceis a root directory, orDestinationis a subdirectory ofSource. chaos. do not.eisdirβDestinationis a directory, butSourceis not.enoentβSourcedoes not exist.enotdirβSourceis a directory, butDestinationis not.exdevβSourceandDestinationare on different file systems. can't cross that bridge, sorry π
script(Filename) -> {ok, Value} | {error, Reason}
Types:
Filename = name_all()
Value = term()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
Reads and evaluates Erlang expressions from the file β separated by . (or ,, because a sequence of expressions is also an expression, iykyk) π
Returns one of the following:
{ok, Value}β the file is read and evaluated.Valueis the value of the last expression. the main character, fr.{error, atom()}β an error occurred when opening the file or reading it. For a list of typical error codes, seeopen/2.{error, {Line, Mod, Term}}β an error occurred when interpreting the Erlang expressions in the file. Useformat_error/1to convert that three-element tuple into an English description of the error π
The encoding of Filename can be set by a comment as described in epp(3erl).
script(Filename, Bindings) -> {ok, Value} | {error, Reason}
Types:
Filename = name_all()
Bindings = erl_eval:binding_struct()
Value = term()
Reason =
posix() |
badarg | terminated | system_limit |
{Line :: integer(), Mod :: module(), Term :: term()}
The same as script/1, but the variable bindings Bindings are used in the evaluation. See erl_eval(3erl) about variable bindings. same script, now with lore πΈ
sendfile(Filename, Socket) -> {ok, integer() >= 0} | {error, inet:posix() | closed | badarg | not_owner}
Types:
Filename = name_all()
Socket =
inet:socket() |
socket:socket() |
fun((iolist()) -> ok | {error, inet:posix() | closed})
Sends the file Filename to Socket. Returns {ok, BytesSent} if successful, otherwise {error, Reason}. zero copies, maximum slay π₯
sendfile(RawFile, Socket, Offset, Bytes, Opts) -> {ok, integer() >= 0} | {error, inet:posix() | closed | badarg | not_owner}
Types:
RawFile = fd()
Socket =
inet:socket() |
socket:socket() |
fun((iolist()) -> ok | {error, inet:posix() | closed})
Offset = Bytes = integer() >= 0
Opts = [sendfile_option()]
sendfile_option() =
{chunk_size, integer() >= 0} | {use_threads, boolean()}
Sends Bytes from the file referenced by RawFile, beginning at Offset, to Socket. Returns {ok, BytesSent} if successful, otherwise {error, Reason}. And if Bytes is set to 0, all data after the specified Offset is sent β the whole rest of it, periodt β¨
β οΈ The file used must be opened using the raw flag, and the process calling sendfile must be the controlling process of the socket. See gen_tcp:controlling_process/2 or module socket's level otp socket option controlling_process. no sneaky side-processes, bestie π
If the OS used does not support non-blocking sendfile, an Erlang fallback using read/2 and gen_tcp:send/2 is used. it'll still get there, just with more steps π¦
Okay so, the option list can contain the following options:
chunk_sizeβ the chunk size the Erlang fallback uses to send data π If youβre using the fallback, set this to a value that comfortably fits in the systemβs memory. Default is20 MB.
π§ set_cwd(Dir) -> ok | {error, Reason}
Types:
Dir = name() | EncodedBinary
EncodedBinary = binary()
Reason = posix() | badarg | no_translation
Sets the current working directory of the file server to Dir. Returns ok if successful.
The functions in the module file usually treat binaries as raw filenames, that is, they are passed βas isβ even when the encoding of the binary does not agree with native_name_encoding(). However, this function expects binaries to be encoded according to the value returned by native_name_encoding().
Typical error reasons are:
enoentβ The directory does not exist.enotdirβ A component ofDiris not a directory. On some platforms,enoentis returned.eaccesβ Missing permission for the directory or one of its parents.badargβDirhas an improper type, such as tuple.no_translationβDiris abinary()with characters coded in ISO-latin-1 and the VM is operating with unicode filename encoding.
β οΈ Warning: In a future release, a bad type for argument Dir will probably generate an exception.
π₯ sync(IoDevice) -> ok | {error, Reason}
Types:
IoDevice = io_device()
Reason = posix() | badarg | terminated
Ensures that any buffers kept by the operating system (not by the Erlang runtime system) are written to disk. On some platforms, this function might have no effect.
A typical error reason is:
enospcβ Not enough space left to write the file.
π§Ή truncate(IoDevice) -> ok | {error, Reason}
Types:
IoDevice = io_device()
Reason = posix() | badarg | terminated
Truncates the file referenced by IoDevice at the current position. Returns ok if successful, otherwise {error, Reason}.
βοΈ write(IoDevice, Bytes) -> ok | {error, Reason}
Types:
IoDevice = io_device() | atom()
Bytes = iodata()
Reason = posix() | badarg | terminated
Writes Bytes to the file referenced by IoDevice. This function is the only way to write to a file opened in raw mode (although it works for normally opened files too). Returns ok if successful, and {error, Reason} otherwise.
If the file is opened with encoding set to something else than latin1, each byte written can result in many bytes being written to the file, as the byte range 0..255 can represent anything between one and four bytes depending on value and UTF encoding type.
Typical error reasons:
ebadfβ The file is not opened for writing.enospcβ No space is left on the device.
βοΈ write_file(Filename, Bytes) -> ok | {error, Reason}
Types:
Filename = name_all()
Bytes = iodata()
Reason = posix() | badarg | terminated | system_limit
Writes the contents of the iodata term Bytes to file Filename. The file is created if it does not exist. If it exists, the previous contents are overwritten. Returns ok if successful, otherwise {error, Reason}.
Typical error reasons:
enoentβ A component of the filename does not exist.enotdirβ A component of the filename is not a directory. On some platforms,enoentis returned instead.enospcβ No space is 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.
βοΈ write_file(Filename, Bytes, Modes) -> ok | {error, Reason}
Types:
Filename = name_all()
Bytes = iodata()
Modes = [mode()]
Reason = posix() | badarg | terminated | system_limit
Same as write_file/2, but takes a third argument Modes, a list of possible modes, see open/2. The mode flags binary and write are implicit, so they are not to be used.
π οΈ write_file_info(Filename, FileInfo) -> ok | {error, Reason} and write_file_info(Filename, FileInfo, Opts) -> ok | {error, Reason}
Types:
Filename = name_all()
Opts = [file_info_option()]
FileInfo = file_info()
Reason = posix() | badarg
Changes file information. Returns ok if successful, otherwise {error, Reason}. FileInfo is a record file_info, defined in the Kernel include file file.hrl. Include the following directive in the module from which the function is called:
-include_lib("kernel/include/file.hrl").
The time type set in atime, mtime, and ctime depends on the time type set in Opts :: {time, Type} as follows:
localβ Interprets the time set as local.universalβ Interprets it as universal time.posixβ Must be seconds since or before Unix time epoch, which is1970-01-01 00:00 UTC.
Default is {time, local}.
If the option raw is set, the file server is not called and only information about local files is returned.
The following fields are used from the record, if they are specified:
atime = date_time() | integer() >= 0β The last time the file was read.mtime = date_time() | integer() >= 0β The last time the file was written.ctime = date_time() | integer() >= 0β On Unix, any value specified for this field is ignored (the βctimeβ for the file is set to the current time). On Windows, this field is the new creation time to set for the file.mode = integer() >= 0β The file permissions as the sum of the following bit values:8#00400β Read permission: owner8#00200β Write permission: owner8#00100β Execute permission: owner8#00040β Read permission: group8#00020β Write permission: group8#00010β Execute permission: group8#00004β Read permission: other8#00002β Write permission: other8#00001β Execute permission: other16#800β Set user id on execution16#400β Set group id on execution
On Unix platforms, other bits than those listed above may be set.
uid = integer() >= 0β Indicates the file owner. Ignored for non-Unix file systems.gid = integer() >= 0β Gives the group that the file owner belongs to. Ignored for non-Unix file systems.
Typical error reasons:
eaccesβ Missing search permission for one of the parent directories of the file.enoentβ The file does not exist.enotdirβ A component of the filename is not a directory. On some platforms,enoentis returned instead.
π₯ POSIX ERROR CODES π₯
Hereβs the full roster the manpage lists β no skips, bestie π
eaccesβ Permission deniedeagainβ Resource temporarily unavailableebadfβ Bad file numberebusyβ File busyedquotβ Disk quota exceededeexistβ File already existsefaultβ Bad address in system call argumentefbigβ File too largeeintrβ Interrupted system calleinvalβ Invalid argumenteioβ I/O erroreisdirβ Illegal operation on a directoryeloopβ Too many levels of symbolic linksemfileβ Too many open filesemlinkβ Too many linksenametoolongβ Filename too longenfileβ File table overflowenodevβ No such deviceenoentβ No such file or directoryenomemβ Not enough memoryenospcβ No space left on deviceenotblkβ Block device requiredenotdirβ Not a directoryenotsupβ Operation not supportedenxioβ No such device or addressepermβ Not ownerepipeβ Broken pipeerofsβ Read-only file systemespipeβ Invalid seekesrchβ No such processestaleβ Stale remote file handleexdevβ Cross-domain link
β‘ PERFORMANCE β‘
Okay bestie, performance tea time. For increased performance, raw files are recommended. Fr fr.
A normal file is really a process, so it can be used as an I/O device (see io). Because of that, when data is written to a normal file, the sending of the data to the file process copies all data that are not binaries. So opening the file in binary mode and writing binaries is therefore recommended. And if the file is opened on another node, or if the file server runs as slave to the file server of another node, also binaries are copied. π
π Note π
Raw files use the file system of the host machine of the node. For normal files (non-raw), the file server is used to find the files, and if the node is running its file server as slave to the file server of another node, and the other node runs on some other host machine, they can have different file systems. However, this is seldom a problem. No cap.
open/2 can be given the options delayed_write and read_ahead to turn on caching, which will reduce the number of operating system calls and greatly improve performance for small reads and writes. But the overhead won't disappear completely, and it's best to keep the number of file operations to a minimum. β¨
As a contrived example, the following function writes 4MB in 2.5 seconds when tested:
create_file_slow(Name) ->
{ok, Fd} = file:open(Name, [raw, write, delayed_write, binary]),
create_file_slow_1(Fd, 4 bsl 20),
file:close(Fd).
create_file_slow_1(_Fd, 0) ->
ok;
create_file_slow_1(Fd, M) ->
ok = file:write(Fd, <<0>>),
create_file_slow_1(Fd, M - 1).
The following functionally equivalent code writes 128 bytes per call to write/2 and so does the same work in 0.08 seconds, which is roughly 30 times faster:
create_file(Name) ->
{ok, Fd} = file:open(Name, [raw, write, delayed_write, binary]),
create_file_1(Fd, 4 bsl 20),
file:close(Fd),
ok.
create_file_1(_Fd, 0) ->
ok;
create_file_1(Fd, M) when M >= 128 ->
ok = file:write(Fd, <<0:(128)/unit:8>>),
create_file_1(Fd, M - 128);
create_file_1(Fd, M) ->
ok = file:write(Fd, <<0:(M)/unit:8>>),
create_file_1(Fd, M - 1).
When writing data it's generally more efficient to write a list of binaries rather than a list of integers. It is not needed to flatten a deep list before writing. On Unix hosts, scatter output, which writes a set of buffers in one operation, is used when possible. In this way write(FD, [Bin1, Bin2 | Bin3]) writes the contents of the binaries without copying the data at all, except for perhaps deep down in the operating system kernel. π₯
β οΈ Warning β οΈ
If an error occurs when accessing an open file with module io, the process handling the file exits. The dead file process can hang if a process tries to access it later. This will be fixed in a future release. π
π SEE ALSO π
And that's the page, bestie! Footer shoutout: Ericsson AB, kernel 8.5.4.2, file(3erl), plus the date line doing its lil timestamp moment. Iconic sign-off behavior, honestly. πβ¨π«Ά
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms