file(3)
π file β the Erlang file interface, bestie edition π
okay so this is file(3), aka the Erlang Module Definition for the file module, and we are about to become SO fluent in file operations it's unreal. grab a boba, we're doing this π§β¨
β¨ NAME β¨
file β the File interface module. that's it, that's the whole vibe. it's your girl for talking to the file system π
πΈ DESCRIPTION πΈ
This module provides an interface to the file system. simple as that, but there's tea to spill first π«
WARNING: File operations are only guaranteed to appear atomic when going through the same file server. A NIF or other OS process may observe intermediate steps on certain operations on some operating systems, eg. renaming an existing file on Windows, or write_file_info/2 on any OS at the time of writing. so likeβ¦ it looks atomic but other processes can absolutely catch you mid-outfit-change π
π filename encoding (the two modes era)
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
latin1mode, the Erlang VM does not change the encoding of filenames. - In
utf8mode, 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. periodt.
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. so you can pick your mode, it's giving choose your own adventure π¦
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. no translation, no notes, she said what she said π
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. know the difference, iykyk π
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 fail. so don't do it. not even a little. not even at the end πΈ
π POSIX Error Codes π
here's the full roster of error atoms, no skips, all of them, because we don't gatekeep:
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-device link
π₯ Performance (the glow-up section) π₯
For increased performance, raw files are recommended. lowkey the move, highkey the move, it's just the move.
A normal file is really a process so it can be used as an I/O device (see io). Therefore, when data is written to a normal file, the sending of the data to the file process, copies all data that are not binaries. Opening the file in binary mode and writing binaries is therefore recommended. 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. π the copying, the copying
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. (she said calmly)
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. However, 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. THIRTY. TIMES. π₯
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. ate that, no crumbs π½οΈπ
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. soβ¦ be aware, bestie π
See Also
filename
π¦ DATA TYPES π¦
date_time() :: calendar:datetime().
Must denote a valid date and time. yes, actually valid. the calendar will know.
deep_list() :: [char() | atom() | deep_list()].delete_option() :: raw.fd() :: file_descriptor().
A file descriptor representing a file opened in raw mode.
file_info() :: #file_info{}.file_info_option() :: {time, local} | {time, universal} | {time, posix} | raw.filename() :: string().
A file name as returned from file API functions.
See the documentation of the name_all/0 type.
filename_all() :: string() | (RawFilename :: binary()).
A file name as returned from file API functions.
See the documentation of the name_all/0 type.
io_device() :: io_server() | fd().
An IO device as returned by open/2.
io_server/0 is returned by default and fd/0 is returned if the raw option is given.
io_server() :: pid().
A process handling the I/O protocol.
location() :: integer() | {bof, Offset :: integer()} | {cur, Offset :: integer()} | {eof, Offset :: integer()} | bof | cur | eof.mode() ::
read | write | append | exclusive | raw | binary |
{delayed_write,
Size :: non_neg_integer(),
Delay :: non_neg_integer()} |
delayed_write |
{read_ahead, Size :: pos_integer()} |
read_ahead | compressed | compressed_one |
{zstd,
zstd:compress_parameters() | zstd:decompress_parameters()} |
{encoding, unicode:encoding()} |
sync.
name() :: string() | atom() | deep_list().
A restricted file name used as input into file API functions.
If VM is in Unicode filename mode, string/0 and char/0 are allowed to be > 255. See also the documentation of the name_all/0 type.
name_all() :: string() | atom() | deep_list() | (RawFilename :: binary()).
A file name used as input into file API functions.
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() ::
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.
posix_file_advise() :: normal | sequential | random | no_reuse | will_need | dont_need.read_file_option() :: raw.sendfile_option() :: {chunk_size, non_neg_integer()} | {use_threads, boolean()}.
π FUNCTIONS π
β advise(IoDevice, Offset, Length, Advise) -> ok | {error, Reason}
when
IoDevice :: io_device(),
Offset :: integer(),
Length :: integer(),
Advise :: posix_file_advise(),
Reason :: posix() | badarg.
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. it's like telling the OS "hey bestie, i'm about to do this, plan accordingly" π«Ά
On some platforms, this function might have no effect. (she's doing her best, okay?)
more parts incoming, don't go anywhere πβ¨
allocate(File, Offset, Length) -> ok | {error, posix()}
when
File :: io_device(),
Offset :: non_neg_integer(),
Length :: non_neg_integer().
Okay so allocate/3 is your preallocate-space-for-a-file bestie β¨. It only succeeds on platforms that actually provide this feature, so no cap β if your platform doesn't have it, it's giving {error, posix()} energy.
change_group(Filename, Gid) -> ok | {error, Reason}
when
Filename :: name_all(),
Gid :: integer(),
Reason :: posix() | badarg.
Changes the group of a file. See write_file_info/2 for the deets π
.
change_mode(Filename, Mode) -> ok | {error, Reason}
when
Filename :: name_all(),
Mode :: integer(),
Reason :: posix() | badarg.
Changes the permissions of a file. See write_file_info/2 π.
change_owner(Filename, Uid) -> ok | {error, Reason}
when
Filename :: name_all(),
Uid :: integer(),
Reason :: posix() | badarg.
Changes the owner of a file. See write_file_info/2 π.
change_owner(Filename, Uid, Gid) -> ok | {error, Reason}
when
Filename :: name_all(),
Uid :: integer(),
Gid :: integer(),
Reason :: posix() | badarg.
Changes the owner and group of a file. See write_file_info/2 π«Ά.
change_time(Filename, Mtime) -> ok | {error, Reason}
when
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}
when
Filename :: name_all(),
Atime :: date_time(),
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}
when
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 optiondelayed_writewas used when opening the file,close/1can return an old write error and not even try to close the file. Seeopen/2. That's lowkey dramatic but fr fr, bestie.
consult(Filename) -> {ok, Terms} | {error, Reason}
when
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 π.
copy(Source, Destination, ByteCount) -> {ok, BytesCopied} | {error, Reason}
when
Source :: io_device() | Filename | {Filename, Modes},
Destination ::
io_device() | Filename | {Filename, Modes},
Filename :: name_all(),
Modes :: [mode()],
ByteCount :: non_neg_integer() | infinity,
BytesCopied :: non_neg_integer(),
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.
Argument Modes is a list of possible modes, see open/2, and defaults to [].
If both Source and Destination refer to filenames, the files are opened with [read, binary] and [write, binary] prepended to their mode lists, respectively, to optimize the copy π₯.
If Source refers to a filename, it is opened with read mode prepended to the mode list before the copy, and closed when done.
If Destination refers to a filename, it is opened with write mode prepended to the mode list before the copy, and closed when done.
Returns {ok, BytesCopied}, where BytesCopied is the number of bytes that was copied, which can 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.
datasync(IoDevice) -> ok | {error, Reason}
when
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. 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 π« .
Applications 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.
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}
when Dir :: name_all(), Reason :: posix() | badarg.
Tries to delete directory Dir. The directory must be empty before it can be deleted. Returns ok if successful.
Typical error reasons:
eaccesβ Missing search or write permissions for the parent directories ofDir.eexistβ The directory is not empty.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}
when File :: name_all(), Reason :: posix() | badarg.
Deletes file or directory File. If File is a directory, its contents is first recursively deleted. Returns:
okβ The operation completed without errors.{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, Opts) -> ok | {error, Reason}
when
Filename :: name_all(),
Opts :: [delete_option()],
Reason :: posix() | badarg.
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.
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.
WARNING: In a future release, a bad type for argument Filename will probably generate an exception.
eval(Filename) -> ok | {error, Reason}
when
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.
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.
eval(Filename, Bindings) -> ok | {error, Reason}
when
Filename :: name_all(),
Bindings :: erl_eval:binding_struct(),
Reason ::
posix() |
badarg | terminated | system_limit |
{Line :: integer(),
Mod :: module(),
Term :: term()}.
Bestie it's literally eval/1 again but now we're passing in variable bindings π
so the evaluation happens with Bindings in play. Wanna know what those bindings actually are under the hood? Go peek at erl_eval. Go on. I'll wait. π«Ά
format_error(Reason) -> Chars
when
Reason ::
posix() |
badarg | terminated | system_limit |
{Line :: integer(),
Mod :: module(),
Term :: term()},
Chars :: string().
You hand it whatever error Reason any function in this module threw at you and it hands you back a Chars string that explains the error in English. Like a google translate for error codes. So helpful it's giving therapist energy. π
get_cwd() -> {ok, Dir} | {error, Reason}
when Dir :: filename(), Reason :: posix().
Returns {ok, Dir} and Dir is the current working directory of the file server. That's it, that's the whole vibe. β¨
NOTE: In rare circumstances this function can fail on Unix π It can happen if read permission doesn't exist for the parent directories of the current directory. So likeβ¦ not usually your fault, but still your problem. π
A typical error reason:
eaccesβ Missing read permission for one of the parents of the current directory.
get_cwd(Drive) -> {ok, Dir} | {error, Reason}
when
Drive :: string(),
Dir :: filename(),
Reason :: posix() | badarg.
Gives you {ok, Dir} or {error, Reason} where Dir is the current working directory of the drive you specified. Drive-core. π
Drive is supposed to be of the form Letter:, for example, .
On platforms that have no concept of a current drive (Unix, for example π), you get {error, enotsup} back. Sorry bestie, no drives here.
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}
when
Dir :: name_all(),
Filenames :: [filename()],
Reason ::
posix() |
badarg |
{no_translation,
Filename :: unicode:latin1_binary()}.
Lists everything in a directoryβ¦ except files with raw filenames. Returns {ok, Filenames} if it slays, otherwise {error, Reason}. Filenames is a list of the names of all the files in the directory. And no, they are not sorted β the universe simply hands them to you in whatever order it feels like. π
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/0with characters coded in ISO Latin-1 and the VM was started with parameter+fnue.
list_dir_all(Dir) -> {ok, Filenames} | {error, Reason}
when
Dir :: name_all(),
Filenames :: [filename_all()],
Reason :: posix() | badarg.
The deluxe version π Lists all the files in a directory, raw filenames included. Returns {ok, Filenames} on success, otherwise {error, Reason}. Filenames is the list of all the names in the directory, and yet again β not sorted. Chaos. We love her. π
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}
when Dir :: name_all(), Reason :: posix() | badarg.
Tries to create directory Dir. Missing parent directories are NOT created β this is not mkdir -p, bestie, don't come for me. Returns ok if it worked. β¨
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. (RIP your storage πͺ¦)enotdirβ A component ofDiris not a directory. On some platforms,enoentis returned instead.
make_link(Existing, New) -> ok | {error, Reason}
when
Existing :: name_all(),
New :: name_all(),
Reason :: posix() | badarg.
Makes a hard link from Existing to New on platforms that support links (Unix and Windows, hiiii π). Returns ok if the link got successfully created, otherwise {error, Reason}. On platforms with no link support at all you get {error,enotsup}. Not supported, not sorry.
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}
when
Existing :: name_all(),
New :: name_all(),
Reason :: posix() | badarg.
Creates a symbolic link New pointing at the file or directory Existing, on platforms that support symbolic links (most Unix systems and Windows, starting with Vista). And here's the iconic part: Existing does not need to exist. Ghost links. Ethereal. π¦ Returns ok if the link was made successfully, otherwise {error, Reason}. On platforms that don't do symbolic links, you get {error, enotsup}.
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's latin1, the system translates no filenames at all β pure, unfiltered, raw. If it's utf8, filenames get converted back and forth to the native filename encoding (usually UTF-8, but UTF-16 on Windows, because of course it is π).
open(File, Modes) -> {ok, IoDevice} | {error, Reason}
when
File :: Filename | iodata(),
Filename :: name_all(),
Modes :: [mode() | ram | directory],
IoDevice :: io_device(),
Reason :: posix() | badarg | system_limit.
Opens file File in whatever mode Modes dictates. Modes can hold one or more of these options, and honestly? It's giving β¨menuβ¨:
readβ The file, which must exist, is opened for reading.writeβ The file is opened for writing. It's created if it doesn't exist. If it does exist andwriteis not combined withread, the file is truncated. π gone. bye.appendβ The file is opened for writing. It's created if it doesn't exist. Every single write operation to a file opened withappendlands at the end of the file.exclusiveβ The file is opened for writing. It's created if it doesn't exist. If the file exists,{error, eexist}comes back at you.
WARNING: This option does not guarantee exclusiveness on file systems that don't support O_EXCL properly, such as NFS. Do not depend on this option unless you know the file system supports it (in general, local file systems are safe). No cap. π«Ά
rawβ Allows faster access to a file, since no Erlang process is needed to handle the file. But a file opened this way comes with the following limitations, and bestie you need to read these:- The functions in the
iomodule cannot be used, because 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. Possessive much?
- 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 the buffered data is written in one operating system call. The buffered data is also flushed before some other file operation thanwrite/2is executed.
The whole point of this option is to boost performance by cutting down the number of operating system calls. So the write/2 calls must be for sizes significantly less than Size, and not interspersed by too many other file operations. π
When this option is used, the result of write/2 calls 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 then not executed. Sneaky. π
For example, when delayed_write is used, after a number of write/2 calls, close/1 can return {error, enospc}, as there is not enough space on the disc for previously written data. close/1 must probably be called again, as the file is still open. Yeah. Read that twice.
delayed_writeβ The same as{delayed_write, Size, Delay}with reasonable default values forSizeandDelay(roughly some 64 KB, 2 seconds). Lazy girl version, and honestly? Valid. π{read_ahead, Size}β turns ON read data buffering. If yourread/2calls are asking for significantly less thanSizebytes, the reads to the operating system still happen in blocks ofSizebytes anyway. That extra data gets buffered and handed back to you on subsequentread/2calls, so you get a performance glow-up because the number of operating system calls goes down. β¨
Lowkey the read_ahead buffer is also super heavily used by read_line/1 in raw mode, so this option is recommended (for performance reasons) when you're accessing raw files with that function. π«Ά
But if your read/2 calls are for sizes not significantly less than Size bytes β or even greater β don't expect any performance gain, bestie. It's just not giving.
read_aheadβ the exact same as{read_ahead, Size}, but 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. Heads up: the file size you get fromread_file_info/1probably does not match the number of bytes you can actually read from a compressed file. π{zstd, Opts}β makes it possible to read or write zstd 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 do automatic translation of characters to and from a specific (Unicode) encoding. Real talk though: the data you hand towrite/2or get back fromread/2is still byte-oriented β this option only says how the data is stored in the disk file.
Depending on the encoding, different methods of reading and writing data are preferred. The default encoding of latin1 implies using this module (file) for reading and writing data, since the interfaces provided here work with byte-oriented data. Using other (Unicode) encodings makes the io functions get_chars, get_line, and put_chars more suitable, because they can work with the full Unicode range. π
If data is sent to an io_device/0 in a format that can't be converted to the specified encoding, or if data is read by a function that returns data in a format that can't cope with the character range of the data, an error occurs and the file is closed. Periodt.
Allowed values for Encoding:
latin1β the default encoding. Bytes supplied to the file, that is,write/2, are written "as is" on the file. Likewise, bytes read from the file, that is,read/2, are returned "as is". If moduleiois used for writing, the file can only cope with Unicode characters up to code point 255 (the ISO Latin-1 range).unicodeorutf8β characters are translated to and from UTF-8 encoding before they're 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.
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. π§
This option is not allowed on raw files.
ramβ file must beiodata/0. Returns anfd/0, which lets modulefileoperate on the data in-memory as if it is a file. π«Άsyncβ on platforms supporting it, enables the POSIXO_SYNCsynchronous I/O flag or its platform-dependent equivalent (for example,FILE_FLAG_WRITE_THROUGHon Windows) so that writes to the file block until the data is physically written to disk. Be aware, though, that the exact semantics of this flag differ from platform to platform. For example, none of Linux or Windows guarantees that all file metadata are also written before the call returns. For precise semantics, check the details of your platform documentation. On platforms with no support for POSIXO_SYNCor equivalent, use of thesyncflag causesopento return{error, enotsup}. πdirectoryβ allowsopento work on directories.
Returns β¨
{ok, IoDevice}β the file is opened in the requested mode.IoDeviceis a reference to the file.{error, Reason}β the file cannot be opened.
IoDevice is really the pid of the process that handles the file. This 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).
WARNING: While this function can be used to open any file, we recommend against using it for NFS-mounted files, FIFOs, devices, or similar since they can cause IO threads to hang forever. If your application needs to interact with these kinds of files we recommend breaking out those parts to a port program instead. π Not me letting an IO thread hang forever, could never.
NOTE: In previous versions offile, modes were specified as one of the atomsread,write, orread_writeinstead of a list. This is still allowed for reasons of backwards compatibility, but is not to be used for new code. Also note thatread_writeis not allowed in a mode list. π
Typical error reasons πΈ
enoentβ the file does not exist.eaccesβ missing permission for reading the file or 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 ifdirectorymode was specified. On some platforms,enoentis returned instead.enospcβ there is no space left on the device (if write access was specified). π
path_consult(Path, Filename)
path_consult(Path, Filename) ->
{ok, Terms, FullName} | {error, Reason}
when
Path :: [Dir],
Dir :: name_all(),
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. Then 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 to an English description of the error.
The encoding of Filename can be set by a comment as described in epp. β¨
path_eval(Path, Filename)
path_eval(Path, Filename) -> {ok, FullName} | {error, Reason}
when
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 reads and evaluates Erlang expressions, separated by . (or ,, a sequence of expressions is also an expression), from the file. Lowkey important: the result of evaluation is not returned β any expression sequence in the file must be there for its side effect. It's giving "we do a little side effecting". π
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}}β something went sideways while the Erlang expressions in the file were being interpreted π nothing you did, bestie. Pass that three-element tuple toformat_error/1and it'll hand you back an actual English sentence explaining the drama.
The encoding of Filename can be set by a comment, exactly as described in epp. π
path_open(Path, Filename, Modes) β {ok, IoDevice, FullName} | {error, Reason}
path_open(Path, Filename, Modes) ->
{ok, IoDevice, FullName} | {error, Reason}
when
Path :: [Dir :: name_all()],
Filename :: name_all(),
Modes :: [mode() | directory],
IoDevice :: io_device(),
FullName :: filename_all(),
Reason :: posix() | badarg | system_limit.
Okay so this one goes hunting π β it walks the path Path (a list of directory names) until it finds Filename. But here's the β¨ twist β¨: if Filename is an absolute filename, Path gets completely ignored, like it doesn't even exist. Then it opens the file in whatever mode Modes says.
You get back one of these:
{ok, IoDevice, FullName}β slay, the file is open in the mode you asked for.IoDeviceis a reference to the file, andFullNameis the file's full name. π{error, enoent}β nope, that file is not in ANY of the directories inPath. it's giving ghosted. π»{error, atom()}β the file exists but refuses to open. rude.
path_script(Path, Filename) β {ok, Value, FullName} | {error, Reason}
path_script(Path, Filename) ->
{ok, Value, FullName} | {error, Reason}
when
Path :: [Dir :: name_all()],
Filename :: name_all(),
Value :: term(),
FullName :: filename_all(),
Reason ::
posix() |
badarg | terminated | system_limit |
{Line :: integer(),
Mod :: module(),
Term :: term()}.
Same treasure hunt as before: it searches Path (a list of directory names, yes) until Filename turns up, and if Filename is absolute then Path is ignored, we said what we said. Then it reads and evaluates the Erlang expressions in the file β separated by . (or ,, and honestly a sequence of expressions is also an expression, that's just how it is) π§
Returns one of:
{ok, Value, FullName}β file read, file evaluated, we ate.FullNameis the full name of the file andValueis the value of the last expression. π{error, enoent}β not in any of the directories inPathbestie, sorry.{error, atom()}β something broke while opening or reading the file. For the roster of typical error codes, go seeopen/2.{error, {Line, Mod, Term}}β interpreting the Erlang expressions in the file went wrong.format_error/1will translate that three-element tuple into plain English for you. π
The encoding of Filename can be set by a comment as described in epp.
path_script(Path, Filename, Bindings) β {ok, Value, FullName} | {error, Reason}
path_script(Path, Filename, Bindings) ->
{ok, Value, FullName} | {error, Reason}
when
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()}.
Literally the same as path_script/2, except the variable bindings in Bindings get used during evaluation. Not sure what a variable binding is? Go read up on erl_eval, it's the whole vibe over there. πΈ
position(IoDevice, Location) β {ok, NewPosition} | {error, Reason}
position(IoDevice, Location) ->
{ok, NewPosition} | {error, Reason}
when
IoDevice :: io_device(),
Location :: location(),
NewPosition :: integer(),
Reason :: posix() | badarg | terminated.
Moves the position of the file that IoDevice points at to Location. If it works you get {ok, NewPosition} as an absolute offset π―, otherwise {error, Reason}. And Location is one of these cuties:
Offsetβ the same thing as{bof, Offset}. twin.{bof, Offset}β absolute offset.{cur, Offset}β offset counted from the current position.{eof, Offset}β offset counted from the end of file.bof | cur | eofβ the same as all of the above but withOffset= 0.
β οΈ Huge heads up bestie: offsets are counted in bytes, not characters. If the file was opened with any encoding other than latin1, one byte β one character, periodt. Positioning in a file like that can only safely land on known character boundaries β meaning a position you got earlier by asking for the current position, or the beginning/end of the file, or some other spot you know for a fact is on a correct character boundary through other means (typically beyond a byte order mark in the file, since that has a known byte size). no cap, don't just yeet a random number in there. π
Typical error reason:
einvalβ eitherLocationis illegal, or it evaluates to a negative offset in the file. π And yeah: if the resulting position is negative, that's an error, and after the call the file position is undefined. chaotic. don't do it.
pread(IoDevice, LocNums) β {ok, DataL} | eof | {error, Reason}
pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason}
when
IoDevice :: io_device(),
LocNums ::
[{Location :: location(),
Number :: non_neg_integer()}],
DataL :: [Data],
Data :: string() | binary() | eof,
Reason :: posix() | badarg | terminated.
Does a whole sequence of pread/3 in one single operation, which is way more efficient than calling them one at a time (the glow-up of batching β¨). Returns {ok, [Data, ...]} or {error, Reason}, where every Data is the result of the matching pread β either a list or a binary depending on the mode of the file, or eof if the position you asked for is beyond the end of file.
π«Ά Since the position is given as a byte-offset, take special caution with files whose encoding isn't latin1, because not every byte position is a valid character boundary in a file like that. iykyk.
pread(IoDevice, Location, Number) β {ok, Data} | eof | {error, Reason}
pread(IoDevice, Location, Number) ->
{ok, Data} | eof | {error, Reason}
when
IoDevice :: io_device(),
Location :: location(),
Number :: non_neg_integer(),
Data :: string() | binary(),
Reason :: posix() | badarg | terminated.
Glues position/2 and read/2 together into one operation β again, more efficient than doing them separately. glow up π
Location is only allowed to be an integer for raw and ram modes.
After the operation, the current position of the file is undefined for raw mode and unchanged for ram mode. yes, undefined. don't ask her where she's been, she doesn't remember. π
πΈ Byte-offset reminder round two: if the file's encoding isn't latin1, be careful, because not every byte position is a valid character boundary on that file.
pwrite(IoDevice, LocBytes) β ok | {error, {N, Reason}}
pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}}
when
IoDevice :: io_device(),
LocBytes ::
[{Location :: location(), Bytes :: iodata()}],
N :: non_neg_integer(),
Reason :: posix() | badarg | terminated.
A sequence of pwrite/3 in one operation, which is β say it with me β more efficient than calling them one at a time. π Returns ok, or {error, {N, Reason}} where N is the number of successful writes that happened before the failure. So you know exactly how far you got before it all fell apart.
When you're positioning in a file with an encoding other thanlatin1, you MUST take caution and set the position on a correct character boundary. Details are inposition/2, go read it.
pwrite(IoDevice, Location, Bytes) β ok | {error, Reason}
pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason}
when
IoDevice :: io_device(),
Location :: location(),
Bytes :: iodata(),
Reason :: posix() | badarg | terminated.
Combines position/2 and write/2 in one operation, which is, you guessed it, 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 thanlatin1, caution must be taken to set the position on a correct character boundary. For the deets, seeposition/2. πΈ
read(IoDevice, Number) β {ok, Data} | eof | {error, Reason}
read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason}
when
IoDevice :: io_device() | io:device(),
Number :: non_neg_integer(),
Data :: string() | binary(),
Reason ::
posix() |
badarg | terminated |
{no_translation, unicode, latin1}.
Reads Number bytes/characters from the file that IoDevice points at. π
Listen, this bit matters: read/2, pread/3, and read_line/1 are the only ways to read from a file opened in raw mode. (They work on normally opened files too, they're just not the only option there.) so if you're in raw mode, that's your whole menu, bestie.
For files where the encoding is set to anything other than latin1, one character might be represented by more than one byte in the file. The Number parameter always means the number of characters read from the file β but the position in the file can scoot forward by a lot more than that number when you're reading a Unicode file. π
Also: if the encoding is set to something other than latin1, the read/2 call fails if the data contains characters larger than 255. Which is exactly why io:get_chars/3 is the preferred move when you're reading a file like that. π¦
The function returns:
{ok, Data}β if the file was opened in binary mode, the read bytes come back in a binary; otherwise they come back in a list. And heads up: the list or binary will be shorter than the number of bytes you requested if end of file was reached.eofβ returned ifNumber>0and end of file was reached before anything at all could be read. like, you asked for bytes and got none bestie π{error, Reason}β something went wrong. the typical reasons are giving:ebadfβ the file is not opened for reading. girl read the room (and also the open mode) π{no_translation, unicode, latin1}β the file is opened with another encoding thanlatin1, and the data in the file cannot be translated to the byte-oriented data that this function returns.
β¨ read_file(Filename, Opts) β¨
read_file(Filename, Opts) -> {ok, Binary} | {error, Reason}
when
Filename :: name_all(),
Opts :: [read_file_option()],
Binary :: binary(),
Reason ::
posix() | badarg | terminated | system_limit.
Returns {ok, Binary}, where Binary is a binary data object that contains the contents of Filename, or {error, Reason} if an error occurs. slay, you got your whole file in one go π«Ά
If the option raw is set, the file server is not called.
Typical error reasons, bestie:
enoentβ the file does not exist. it's not there. it's giving nothing πeaccesβ missing permission for reading the file, or for searching one of the parent directories.eisdirβ the named file is a directory. that's a folder, not a file, babe π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, Opts) π
read_file_info(File, Opts) -> {ok, FileInfo} | {error, Reason}
when
File :: name_all() | io_device(),
Opts :: [file_info_option()],
FileInfo :: file_info(),
Reason :: posix() | badarg.
Retrieves information about a file. Returns {ok, FileInfo} if successful, otherwise {error, Reason}. iykyk β¨
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 returned in atime, mtime, and ctime is dependent on the time type set in Opts :: {time, Type} as follows:
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 as it can race with a concurrent call to write_file_info/1,2. no cap, that's a race condition and races are not it πββοΈπ¨
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. speed, we love to see it π₯
The record file_info contains the following fields:
- **
size= **non_neg_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/0 | non_neg_integer/0β the last time the file was read. - **
mtime= **date_time/0 | non_neg_integer/0β the last time the file was written. - **
ctime= **date_time/0 | non_neg_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= **non_neg_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= **non_neg_integer/0β number of links to the file (this is always1for file systems that have no concept of links). - **
major_device= **non_neg_integer/0β identifies the file system where the file is located. In Windows, the number indicates a drive as follows:0meansA:,1meansB:, and so on. - **
minor_device= **non_neg_integer/0β only valid for character devices on Unix. In all other cases, this field is zero. - **
inode= **non_neg_integer/0β gives the inode number. On non-Unix file systems, this field is zero. - **
uid= **non_neg_integer/0β indicates the owner of the file. On non-Unix file systems, this field is zero. - **
gid= **non_neg_integer/0β gives the group that the owner of the file belongs to. On non-Unix file systems, this field is zero.
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.
πΈ read_line(IoDevice) πΈ
read_line(IoDevice) -> {ok, Data} | eof | {error, Reason}
when
IoDevice :: io_device() | io:device(),
Data :: string() | binary(),
Reason ::
posix() |
badarg | terminated |
{no_translation, unicode, latin1}.
Reads a line of bytes/characters from the file referenced by IoDevice. one line at a time, no biggie π
Lines are defined to be delimited by the linefeed (LF, \n) character, but any carriage return (CR, \r) followed by a newline is also treated as a single LF character (the carriage return is silently ignored). The line is returned including the LF, but excluding any CR immediately followed by an LF. This behaviour is consistent with the behaviour of io:get_line/2. If end of file is reached without any LF ending the last line, a line with no trailing LF is returned. periodt π
The function can be used on files opened in raw mode. However, it is inefficient to use it on raw files if the file is not opened with option {read_ahead, Size} specified. Thus, combining raw and {read_ahead, Size} is highly recommended when opening a text file for raw line-oriented reading. do both or you're gonna have a bad time π
If encoding is set to something else than latin1, the read_line/1 call fails if the data contains characters larger than 255, why io:get_line/2 is to be preferred when reading such a file.
The function returns:
{ok, Data}β one line from the file is returned, 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 are returned in a binary, otherwise in a list.
eofβ returned if 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 on the file cannot be translated to the byte-oriented data that this function returns.
π¦ read_link(Name) π¦
read_link(Name) -> {ok, Filename} | {error, Reason}
when
Name :: name_all(),
Filename :: filename(),
Reason :: posix() | badarg.
Returns {ok, Filename} if Name refers to a symbolic link that is not a raw filename, or {error, Reason} otherwise. On platforms that do not support symbolic links, the return value is {error,enotsup}. where does it point tho π
Typical error reasons:
einvalβNamedoes not refer to a symbolic link or the name of the file that 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.
π read_link_all(Name) π
read_link_all(Name) -> {ok, Filename} | {error, Reason}
when
Name :: name_all(),
Filename :: filename_all(),
Reason :: posix() | badarg.
Returns {ok, Filename} if Name refers to a symbolic link or {error, Reason} otherwise. On platforms that do not support symbolic links, the return value is {error, enotsup}.
Notice that Filename can be either a list or a binary. flexible queen π
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, Opts) π
read_link_info(Name, Opts) -> {ok, FileInfo} | {error, Reason}
when
Name :: name_all(),
Opts :: [file_info_option()],
FileInfo :: file_info(),
Reason :: posix() | badarg.
Works like read_file_info/1,2 except that if Name is a symbolic link, information about the link is returned in the file_info record and the type field of the record is set to symlink. it tells you about the link itself, not where it goes β iconic behavior β¨
If the option raw is set, the file server does not get called and you only get info about local files back. Heads up tho β this breaks the module's atomicity guarantees, because it can race with a concurrent call to write_file_info/1,2. Live your life, but know that's the vibe π
If Name isn't a symbolic link, this function returns the same result as read_file_info/1. And on platforms that don't do symbolic links at all? It's always equivalent to read_file_info/1. Period, no notes. β¨
rename/2 π·οΈ
rename(Source, Destination) -> ok | {error, Reason}
when
Source :: name_all(),
Destination :: name_all(),
Reason :: posix() | badarg.
Tries to rename the file Source to Destination. It can also move files (and directories) between directories, but bestie listen β you can't just slap the destination directory in there. The destination filename must be specified too. π
So like, if bar is a normal file and foo and baz are directories:
rename("foo/bar", "baz")β returns an error π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). Do not come for me when it fails.
Typical error reasons, the whole roster:
eaccesβ missing read or write permissions for the parent directories ofSourceorDestination. On some platforms, you get this one 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.eisdirβDestinationis a directory, butSourceis not.enoentβSourcedoes not exist. πenotdirβSourceis a directory, butDestinationis not.exdevβSourceandDestinationare on different file systems. π
script/1 π
script(Filename) -> {ok, Value} | {error, Reason}
when
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, andValueis the value of the last expression. Iconic.{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.
script/2 π
script(Filename, Bindings) -> {ok, Value} | {error, Reason}
when
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, except the variable bindings Bindings are used in the evaluation. See erl_eval about variable bindings. β¨
sendfile/2 π€
sendfile(Filename, Socket) ->
{ok, non_neg_integer()} |
{error, inet:posix() | closed | badarg | not_owner}
when
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 it went slay, otherwise {error, Reason}. π¦
sendfile/5 π₯
sendfile(RawFile, Socket, Offset, Bytes, Opts) ->
{ok, non_neg_integer()} |
{error, inet:posix() | closed | badarg | not_owner}
when
RawFile :: fd(),
Socket ::
inet:socket() |
socket:socket() |
fun((iolist()) ->
ok | {error, inet:posix() | closed}),
Offset :: non_neg_integer(),
Bytes :: non_neg_integer(),
Opts :: [sendfile_option()].
Sends Bytes from the file referenced by RawFile, starting at Offset, to Socket. Returns {ok, BytesSent} if it's successful, otherwise {error, Reason}. If Bytes is set to 0, all data after the specified Offset gets sent. π
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. π
If the OS you're on doesn't support non-blocking sendfile, an Erlang fallback using read/2 and gen_tcp:send/2 is used instead. No cap.
The option list can contain the following option:
chunk_sizeβ the chunk size used by the Erlang fallback 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/1 π
set_cwd(Dir) -> ok | {error, Reason}
when
Dir :: name() | EncodedBinary,
EncodedBinary :: binary(),
Reason :: posix() | badarg | no_translation.
Sets the current working directory of the file server to Dir. Returns ok if it's successful. β¨
The functions in module file usually treat binaries as raw filenames β meaning they're passed "as is" even when the encoding of the binary doesn't agree with native_name_encoding(). BUT this function is different: it expects binaries to be encoded according to whatever native_name_encoding/0 returns. Mind the gap bestie π
Typical error reasons are:
enoentβ the directory does not exist.enotdirβ a component ofDiris not a directory. On some platforms,enoentis returned instead.eaccesβ missing permission for the directory or one of its parents.badargβDirhas an improper type, such as tuple.no_translationβDiris abinary/0with 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. They said what they said.
sync/1 πΎ
sync(IoDevice) -> ok | {error, Reason}
when
IoDevice :: io_device(),
Reason :: posix() | badarg | terminated.
Ensures that any buffers kept by the operating system (not by the Erlang runtime system, just to be clear) get written to disk. On some platforms this function might have no effect at all β it's giving vibes only π
A typical error reason is:
enospcβ not enough space left to write the file.
truncate/1 βοΈ
truncate(IoDevice) -> ok | {error, Reason}
when
IoDevice :: io_device(),
Reason :: posix() | badarg | terminated.
Truncates the file referenced by IoDevice at the current position. Returns ok if it's successful, otherwise {error, Reason}. Chop chop πΈ
write/2 βοΈ
write(IoDevice, Bytes) -> ok | {error, Reason}
when
IoDevice :: io_device() | io:device(),
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 (though it works for normally opened files too, no shade). Returns ok if it's successful, and {error, Reason} otherwise. π
If the file is opened with encoding set to something other than latin1, each byte written can result in many bytes being written to the file β because the byte range 0..255 can represent anything between one and four bytes, depending on value and UTF encoding type. Lowkey wild. If you want to write unicode:chardata/0 to the IoDevice, you should use io:put_chars/2 instead. π
Typical error reasons:
ebadfβ the file is not opened for writing.enospcβ no space is left on the device.
write_file/2 π
write_file(Filename, Bytes) -> ok | {error, Reason}
when
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 does exist, the previous contents are overwritten β gone, deceased, rest in peace π Returns ok if it's 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/3 π
write_file(Filename, Bytes, Modes) -> ok | {error, Reason}
when
Filename :: name_all(),
Bytes :: iodata(),
Modes :: [mode()],
Reason ::
posix() | badarg | terminated | system_limit.
Same as write_file/2, but it takes a third argument Modes, a list of possible modes β see open/2. Important: the mode flags binary and write are implicit, so they are not to be used. Don't add them, bestie, they're already handled π«Ά
write_file_info(Filename, FileInfo, Opts) -> ok | {error, Reason}
when
Filename :: name_all(),
Opts :: [file_info_option()],
FileInfo :: file_info(),
Reason :: posix() | badarg.
okay so this one changes file information π
Returns ok if it ate, otherwise {error, Reason}. And Reason is posix() | badarg, iykyk.
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}. Periodt β¨
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/0 | non_neg_integer/0β The last time the file was read.mtime = date_time/0 | non_neg_integer/0β The last time the file was written.ctime = date_time/0 | non_neg_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 = non_neg_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 = non_neg_integer/0β Indicates the file owner. Ignored for non-Unix file systems.gid = non_neg_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.
and that's the whole page, bestie π«Ά this masterpiece was brought to you by Ericsson AB, kernel 11.0.3, file(3) β mwah πβ¨
π¦ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms