file(kernel v10.3.1)
View SourceFile interface module.
This module provides an interface to the file system.
Warning
File operations are only guaranteed to appear atomic when going through thesame file server. A NIF or other OS process may observe intermediate steps oncertain operations on some operating systems, eg. renaming an existing file onWindows, orwrite_file_info/2
on any OS at the timeof writing.
Regarding filename encoding, the Erlang VM can operate in two modes. The currentmode can be queried using functionnative_name_encoding/0
. It returnslatin1
orutf8
.
Inlatin1
mode, the Erlang VM does not change the encoding of filenames. Inutf8
mode, filenames can contain Unicode characters greater than 255 and theVM converts filenames back and forth to the native filename encoding (usuallyUTF-8, but UTF-16 on Windows).
The default mode depends on the operating system. Windows, MacOS X and Androidenforce consistent filename encoding and therefore the VM usesutf8
mode.
On operating systems with transparent naming (for example, all Unix systemsexcept MacOS X), default isutf8
if the terminal supports UTF-8, otherwiselatin1
. The default can be overridden using+fnl
(to forcelatin1
mode) or+fnu
(to forceutf8
mode) when startingerl
.
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 ISOLatin-1. The concept ofraw filenames is introduced to handle file systemswith inconsistent naming when running inutf8
mode.
Araw filename is a filename specified as a binary. The Erlang VM does nottranslate a filename specified as a binary on systems with transparent naming.
When running inutf8
mode, functionslist_dir/1
andread_link/1
neverreturn raw filenames. To return all filenames including raw filenames, usefunctionslist_dir_all/1
andread_link_all/1
.
See also sectionNotes About Raw Filenamesin the STDLIB User's Guide.
Note
File operations used to accept filenames containing null characters (integervalue zero). This caused the name to be truncated and in some cases argumentsto primitive operations to be mixed up. Filenames containing null charactersinside the filename are nowrejected and will cause primitive fileoperations fail.
POSIX Error Codes
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
For increased performance, raw files are recommended.
A normal file is really a process so it can be used as an I/O device (seeio
). Therefore, when data is written to a normal file, the sending of thedata to the file process, copies all data that are not binaries. Opening thefile in binary mode and writing binaries is therefore recommended. If the fileis opened on another node, or if the file server runs as slave to the fileserver of another node, also binaries are copied.
Note
Raw files use the file system of the host machine of the node. For normalfiles (non-raw), the file server is used to find the files, and if the node isrunning its file server as slave to the file server of another node, and theother node runs on some other host machine, they can have different filesystems. However, this is seldom a problem.
open/2
can be given the optionsdelayed_write
andread_ahead
to turn oncaching, which will reduce the number of operating system calls and greatlyimprove performance for small reads and writes. However, the overhead won'tdisappear completely and it's best to keep the number of file operations to aminimum. As a contrived example, the following function writes 4MB in 2.5seconds when tested:
create_file_slow(Name)->{ok,Fd}=file:open(Name,[raw,write,delayed_write,binary]),create_file_slow_1(Fd,4bsl20),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 towrite/2
and so does the same work in 0.08 seconds, which is roughly 30 timesfaster:
create_file(Name)->{ok,Fd}=file:open(Name,[raw,write,delayed_write,binary]),create_file_1(Fd,4bsl20),file:close(Fd),ok.create_file_1(_Fd,0)->ok;create_file_1(Fd,M)whenM>=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 binariesrather than a list of integers. It is not needed to flatten a deep list beforewriting. On Unix hosts, scatter output, which writes a set of buffers in oneoperation, is used when possible. In this waywrite(FD, [Bin1, Bin2 | Bin3])
writes the contents of thebinaries without copying the data at all, except for perhaps deep down in theoperating system kernel.
Warning
If an error occurs when accessing an open file with moduleio
, the processhandling the file exits. The dead file process can hang if a process tries toaccess it later. This will be fixed in a future release.
See Also
Summary
Types
Must denote a valid date and time.
A file name as returned fromfile
API functions.
A file name as returned fromfile
API functions.
An IO device as returned byopen/2
.
A process handling the I/O protocol.
A file name used as input intofile
API functions.
An atom that is named from the POSIX error codes used in Unix, and in theruntime libraries of most C compilers.
Functions
advise/4
can be used to announce an intention to access filedata in a specific pattern in the future, thus allowing the operating system toperform appropriate optimizations.
allocate/3
can be used to preallocate space for a file.
Changes group of a file. Seewrite_file_info/2
.
Changes permissions of a file. Seewrite_file_info/2
.
Changes owner of a file. Seewrite_file_info/2
.
Changes owner and group of a file. Seewrite_file_info/2
.
Changes the modification and access times of a file. Seewrite_file_info/2
.
Changes the modification and last access times of a file. Seewrite_file_info/2
.
Closes the file referenced byIoDevice
. It mostly returnsok
, except forsome severe errors such as out of memory.
Reads Erlang terms, separated by.
, fromFilename
. Returns one of thefollowing
CopiesByteCount
bytes fromSource
toDestination
.Source
andDestination
refer to either filenames or IO devices from, for example,open/2
.
Ensures that any buffers kept by the operating system (not by the Erlang runtimesystem) are written to disk. In many ways it resemblesfsync
but it does notupdate some of the metadata of the file, such as the access time. On someplatforms this function has no effect.
Tries to delete directoryDir
. The directory must be empty before it can bedeleted. Returnsok
if successful.
Deletes file or directoryFile
. IfFile
is a directory, its contents isfirst recursively deleted. Returns
Equivalent todelete(Filename, [])
.
Tries to delete fileFilename
. Returnsok
if successful.
Reads and evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression) fromFilename
. The result of the evaluationis not returned; any expression sequence in the file must be there for its sideeffect.
Given the error reason returned by any function in this module, returns adescriptive string of the error in English.
Returns{ok, Dir}
, whereDir
is the current working directory of the fileserver.
Returns{ok, Dir}
or{error, Reason}
, whereDir
is the current workingdirectory of the specified drive.
Lists all files in a directory,except files with raw filenames. Returns{ok, Filenames}
if successful, otherwise{error, Reason}
.Filenames
is alist of the names of all the files in the directory. The names are not sorted.
Lists all the files in a directory, including files withraw filenames. Returns{ok, Filenames}
if successful, otherwise{error, Reason}
.Filenames
is a list of the names of all the files in thedirectory. The names are not sorted.
Tries to create directoryDir
. Missing parent directories arenot created.Returnsok
if successful.
Makes a hard link fromExisting
toNew
on platforms supporting links (Unixand Windows). This function returnsok
if the link was successfully created,otherwise{error, Reason}
. On platforms not supporting links,{error,enotsup}
is returned.
Creates a symbolic linkNew
to the file or directoryExisting
on platformssupporting symbolic links (most Unix systems and Windows, beginning with Vista).Existing
does not need to exist. Returnsok
if the link is successfullycreated, otherwise{error, Reason}
. On platforms not supporting symboliclinks,{error, enotsup}
is returned.
Returns the filename encoding mode. If it islatin1
, the system translates nofilenames. If it isutf8
, filenames are converted back and forth to the nativefilename encoding (usually UTF-8, but UTF-16 on Windows).
Opens fileFile
in the mode determined byModes
, which can contain one ormore of the following options
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsErlang terms, separated by.
, from the file.
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsand evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file. The result of evaluation isnot returned; any expression sequence in the file must be there for its sideeffect.
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then opensthe file in the mode determined byModes
.
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsand evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file.
The same aspath_script/2
but the variable bindingsBindings
are used in the evaluation. Seeerl_eval
about variable bindings.
Sets the position of the file referenced byIoDevice
toLocation
. Returns{ok, NewPosition}
(as absolute offset) if successful, otherwise{error, Reason}
.Location
is one of the following
Performs a sequence ofpread/3
in one operation, which is moreefficient than calling them one at a time. Returns{ok, [Data, ...]}
or{error, Reason}
, where eachData
, the result of the correspondingpread
,is either a list or a binary depending on the mode of the file, oreof
if therequested position is beyond end of file.
Combinesposition/2
andread/2
in one operation,which is more efficient than calling them one at a time.
Performs a sequence ofpwrite/3
in one operation, which is moreefficient than calling them one at a time. Returnsok
or{error, {N, Reason}}
, whereN
is the number of successful writes done beforethe failure.
Combinesposition/2
andwrite/2
in oneoperation, which is more efficient than calling them one at a time.
ReadsNumber
bytes/characters from the file referenced byIoDevice
.
Equivalent toread_file(Filename, [])
.
Returns{ok, Binary}
, whereBinary
is a binary data object that contains thecontents ofFilename
, or{error, Reason}
if an error occurs.
Equivalent toread_file_info(File, [])
.
Retrieves information about a file. Returns{ok, FileInfo}
if successful,otherwise{error, Reason}
.
Reads a line of bytes/characters from the file referenced byIoDevice
.
Returns{ok, Filename}
ifName
refers to a symboliclink that is not a raw filename, or{error, Reason}
otherwise. On platformsthat do not support symbolic links, the return value is{error,enotsup}
.
Returns{ok, Filename}
ifName
refers to a symbolic link or{error, Reason}
otherwise. On platforms that do not support symbolic links,the return value is{error,enotsup}
.
Equivalent toread_link_info(Name, [])
.
Works likeread_file_info/1,2
except that ifName
is asymbolic link, information about the link is returned in thefile_info
recordand thetype
field of the record is set tosymlink
.
Tries to rename the fileSource
toDestination
. It can be used to move files(and directories) between directories, but it is not sufficient to specify thedestination only. The destination filename must also be specified. For example,ifbar
is a normal file andfoo
andbaz
are directories,rename("foo/bar", "baz")
returns an error, butrename("foo/bar", "baz/bar")
succeeds. Returnsok
if it issuccessful.
Reads and evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file.
Sends the fileFilename
toSocket
. Returns{ok, BytesSent}
if successful,otherwise{error, Reason}
.
SendsBytes
from the file referenced byRawFile
beginning atOffset
toSocket
. Returns{ok, BytesSent}
if successful, otherwise{error, Reason}
.IfBytes
is set to0
all data after the specifiedOffset
is sent.
Sets the current working directory of the file server toDir
. Returnsok
ifsuccessful.
Ensures that any buffers kept by the operating system (not by the Erlang runtimesystem) are written to disk. On some platforms, this function might have noeffect.
Truncates the file referenced byIoDevice
at the current position. Returnsok
if successful, otherwise{error, Reason}
.
WritesBytes
to the file referenced byIoDevice
. This function is the onlyway to write to a file opened inraw
mode (although it works for normallyopened files too). Returnsok
if successful, and{error, Reason}
otherwise.
Writes the contents of theiodata
termBytes
to fileFilename
. The file iscreated if it does not exist. If it exists, the previous contents areoverwritten. Returnsok
if successful, otherwise{error, Reason}
.
Same aswrite_file/2
, but takes a third argumentModes
, alist of possible modes, seeopen/2
. The mode flagsbinary
andwrite
areimplicit, so they are not to be used.
Changes file information. Returnsok
if successful, otherwise{error, Reason}
.
Types
-type date_time() ::calendar:datetime().
Must denote a valid date and time.
-type delete_option() :: raw.
-type fd() :: file_descriptor().
A file descriptor representing a file opened inraw
mode.
-type file_info() :: #file_info{size ::non_neg_integer() | undefined, type :: device | directory | other | regular | symlink | undefined, access :: read | write | read_write | none | undefined, atime ::file:date_time() |non_neg_integer() | undefined, mtime ::file:date_time() |non_neg_integer() | undefined, ctime ::file:date_time() |non_neg_integer() | undefined, mode ::non_neg_integer() | undefined, links ::non_neg_integer() | undefined, major_device ::non_neg_integer() | undefined, minor_device ::non_neg_integer() | undefined, inode ::non_neg_integer() | undefined, uid ::non_neg_integer() | undefined, gid ::non_neg_integer() | undefined}.
-type file_info_option() :: {time, local} | {time, universal} | {time, posix} | raw.
-type filename() ::string().
A file name as returned fromfile
API functions.
See the documentation of thename_all/0
type.
A file name as returned fromfile
API functions.
See the documentation of thename_all/0
type.
An IO device as returned byopen/2
.
io_server/0
is returned by default andfd/0
is returned if theraw
option is given.
-type io_server() ::pid().
A process handling the I/O protocol.
-type 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 | {encoding,unicode:encoding()} | sync.
A restricted file name used as input intofile
API functions.
If VM is in Unicode filename mode,string/0
andchar/0
are allowed tobe > 255. See also the documentation of thename_all/0
type.
A file name used as input intofile
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 itcan contain characters not conforming to the Unicode encoding expected from thefile system (that is, non-UTF-8 characters although the VM is started in Unicodefilename mode). Null characters (integer value zero) arenot allowed infilenames (not even at the end).
-type 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 theruntime libraries of most C compilers.
-type posix_file_advise() :: normal | sequential | random | no_reuse | will_need | dont_need.
-type read_file_option() :: raw.
-type sendfile_option() :: {chunk_size,non_neg_integer()} | {use_threads,boolean()}.
Functions
-spec 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 filedata in a specific pattern in the future, thus allowing the operating system toperform appropriate optimizations.
On some platforms, this function might have no effect.
-spec allocate(File, Offset, Length) -> ok | {error,posix()} when File ::io_device(), Offset ::non_neg_integer(), Length ::non_neg_integer().
allocate/3
can be used to preallocate space for a file.
This function only succeeds in platforms that provide this feature.
-spec change_group(Filename, Gid) -> ok | {error, Reason} when Filename ::name_all(), Gid ::integer(), Reason ::posix() | badarg.
Changes group of a file. Seewrite_file_info/2
.
-spec change_mode(Filename, Mode) -> ok | {error, Reason} when Filename ::name_all(), Mode ::integer(), Reason ::posix() | badarg.
Changes permissions of a file. Seewrite_file_info/2
.
-spec change_owner(Filename, Uid) -> ok | {error, Reason} when Filename ::name_all(), Uid ::integer(), Reason ::posix() | badarg.
Changes owner of a file. Seewrite_file_info/2
.
-spec change_owner(Filename, Uid, Gid) -> ok | {error, Reason} when Filename ::name_all(), Uid ::integer(), Gid ::integer(), Reason ::posix() | badarg.
Changes owner and group of a file. Seewrite_file_info/2
.
-spec 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. Seewrite_file_info/2
.
-spec 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. Seewrite_file_info/2
.
-spec close(IoDevice) -> ok | {error, Reason} when IoDevice ::io_device(), Reason ::posix() | badarg | terminated.
Closes the file referenced byIoDevice
. It mostly returnsok
, except forsome severe errors such as out of memory.
Notice that if optiondelayed_write
was used when opening the file,close/1
can return an old write error and not even try to closethe file. Seeopen/2
.
-spec 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.
, fromFilename
. Returns one of thefollowing:
{ok, Terms}
- The file was successfully read.{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 theErlang terms in the file. To convert the three-element tuple to an Englishdescription 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 ofFilename
can be set by a comment, as described inepp
.
-spec copy(Source, Destination) -> {ok, BytesCopied} | {error, Reason} when Source ::io_device() | Filename | {Filename, Modes}, Destination ::io_device() | Filename | {Filename, Modes}, Filename ::name_all(), Modes :: [mode()], BytesCopied ::non_neg_integer(), Reason ::posix() | badarg | terminated.
Equivalent tocopy(Source, Destination, infinity)
.
-spec 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.
CopiesByteCount
bytes fromSource
toDestination
.Source
andDestination
refer to either filenames or IO devices from, for example,open/2
.
ArgumentModes
is a list of possible modes, seeopen/2
, and defaults to[]
.
If bothSource
andDestination
refer to filenames, the files are opened with[read, binary]
and[write, binary]
prepended to their mode lists,respectively, to optimize the copy.
IfSource
refers to a filename, it is opened withread
mode prepended to themode list before the copy, and closed when done.
IfDestination
refers to a filename, it is opened withwrite
mode prependedto the mode list before the copy, and closed when done.
Returns{ok, BytesCopied}
, whereBytesCopied
is the number of bytes that wascopied, which can be less thanByteCount
if end of file was encountered on thesource. If the operation fails,{error, Reason}
is returned.
Typical error reasons: as foropen/2
if a file had to be opened, and as forread/2
andwrite/2
.
-spec 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 runtimesystem) are written to disk. In many ways it resemblesfsync
but it does notupdate some of the metadata of the file, such as the access time. On someplatforms 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 callfsync()
immediately toensure that the written data is physically stored on the hard disk.Unfortunately,fsync()
always initiates two write operations: one for thenewly written data and another one to update the modification time stored in theinode
. If the modification time is not a part of the transaction concept,fdatasync()
can be used to avoid unnecessaryinode
disk write operations.
Available only in some POSIX systems, this call results in a call tofsync()
,or has no effect in systems not providing thefdatasync()
syscall.
Tries to delete directoryDir
. The directory must be empty before it can bedeleted. Returnsok
if successful.
Typical error reasons:
eacces
- Missing search or write permissions for the parent directoriesofDir
.eexist
- The directory is not empty.enoent
- The directory does not exist.enotdir
- A component ofDir
is not a directory. On some platforms,enoent
is returned instead.einval
- Attempt to delete the current directory. On some platforms,eacces
is returned instead.
Deletes file or directoryFile
. IfFile
is a directory, its contents isfirst recursively deleted. Returns:
ok
- The operation completed without errors.{error, posix()}
- An error occurred when accessing or deletingFile
.If some file or directory underFile
could not be deleted,File
cannot bedeleted as it is non-empty, and{error, eexist}
is returned.
-spec delete(Filename) -> ok | {error, Reason} when Filename ::name_all(), Reason ::posix() | badarg.
Equivalent todelete(Filename, [])
.
-spec delete(Filename, Opts) -> ok | {error, Reason} when Filename ::name_all(), Opts :: [delete_option()], Reason ::posix() | badarg.
Tries to delete fileFilename
. Returnsok
if successful.
If the optionraw
is set, the file server is not called. This can be useful inparticular during the early boot stage when the file server is not yetregistered, 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 someplatforms,enoent
is returned instead.einval
-Filename
has an improper type, such as tuple.
Warning
In a future release, a bad type for argumentFilename
will probably generatean exception.
-spec 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 ofexpressions is also an expression) fromFilename
. The result of the evaluationis not returned; any expression sequence in the file must be there for its sideeffect.
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 theErlang expressions in the file. To convert the three-element tuple to anEnglish description of the error, useformat_error/1
.
The encoding ofFilename
can be set by a comment, as described inepp
.
-spec 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()}.
The same aseval/1
, but the variable bindingsBindings
are usedin the evaluation. For information about the variable bindings, seeerl_eval
.
-spec format_error(Reason) -> Chars when 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 adescriptive string of the error in English.
Returns{ok, Dir}
, whereDir
is the current working directory of the fileserver.
Note
In rare circumstances, this function can fail on Unix. It can occur if readpermission 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 currentdirectory.
-spec get_cwd(Drive) -> {ok, Dir} | {error, Reason} when Drive ::string(), Dir ::filename(), Reason ::posix() | badarg.
Returns{ok, Dir}
or{error, Reason}
, whereDir
is the current workingdirectory of the specified drive.
Drive
is to be of the formLetter:
, for example,c:
.
Returns{error, enotsup}
on platforms that have no concept of current drive(Unix, for example).
Typical error reasons:
enotsup
- The operating system has no concept of drives.eacces
- The drive does not exist.einval
- The format ofDrive
is invalid.
-spec list_dir(Dir) -> {ok, Filenames} | {error, Reason} when 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 alist of the names of all the files in the directory. The names are not sorted.
Typical error reasons:
eacces
- Missing search or write permissions forDir
or one of itsparent directories.enoent
- The directory does not exist.{no_translation, Filename}
-Filename
is abinary/0
withcharacters coded in ISO Latin-1 and the VM was started with parameter+fnue
.
-spec list_dir_all(Dir) -> {ok, Filenames} | {error, Reason} when Dir ::name_all(), Filenames :: [filename_all()], Reason ::posix() | badarg.
Lists all the files in a directory, including files withraw filenames. Returns{ok, Filenames}
if successful, otherwise{error, Reason}
.Filenames
is a list of the names of all the files in thedirectory. The names are not sorted.
Typical error reasons:
eacces
- Missing search or write permissions forDir
or one of itsparent directories.enoent
- The directory does not exist.
Tries to create directoryDir
. Missing parent directories arenot created.Returnsok
if successful.
Typical error reasons:
eacces
- Missing search or write permissions for the parent directoriesofDir
.eexist
- A file or directory namedDir
exists already.enoent
- A component ofDir
does not exist.enospc
- No space is left on the device.enotdir
- A component ofDir
is not a directory. On some platforms,enoent
is returned instead.
-spec make_link(Existing, New) -> ok | {error, Reason} when Existing ::name_all(), New ::name_all(), Reason ::posix() | badarg.
Makes a hard link fromExisting
toNew
on platforms supporting links (Unixand Windows). This function returnsok
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 ofExisting
orNew
.eexist
-New
already exists.enotsup
- Hard links are not supported on this platform.
-spec make_symlink(Existing, New) -> ok | {error, Reason} when Existing ::name_all(), New ::name_all(), Reason ::posix() | badarg.
Creates a symbolic linkNew
to the file or directoryExisting
on platformssupporting symbolic links (most Unix systems and Windows, beginning with Vista).Existing
does not need to exist. Returnsok
if the link is successfullycreated, otherwise{error, Reason}
. On platforms not supporting symboliclinks,{error, enotsup}
is returned.
Typical error reasons:
eacces
- Missing read or write permissions for the parent directories ofExisting
orNew
.eexist
-New
already exists.enotsup
- Symbolic links are not supported on this platform.eperm
- User does not have privileges to create symbolic links(SeCreateSymbolicLinkPrivilege
on Windows).
-spec native_name_encoding() -> latin1 | utf8.
Returns the filename encoding mode. If it islatin1
, the system translates nofilenames. If it isutf8
, filenames are converted back and forth to the nativefilename encoding (usually UTF-8, but UTF-16 on Windows).
-spec 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 fileFile
in the mode determined byModes
, which can contain one ormore 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 notexist. If the file exists andwrite
is not combined withread
, the file istruncated.append
- The file is opened for writing. It is created if it does notexist. Every write operation to a file opened withappend
takes place at theend of the file.exclusive
- The file is opened for writing. It is created if it does notexist. If the file exists,{error, eexist}
is returned.Warning
This option does not guarantee exclusiveness on file systems not supporting
O_EXCL
properly, such as NFS. Do not depend on this option unless you knowthat the file system supports it (in general, local file systems are safe).raw
- Allows faster access to a file, as no Erlang processis needed to handle the file. However, a file opened in this way has thefollowing limitations:- The functions in the
io
module cannot be used, as they can only talk to anErlang process. Instead, use functionsread/2
,read_line/1
, andwrite/2
. - Especially if
read_line/1
is to be used on araw
file,it is recommended to combine this option with option{read_ahead, Size}
asline-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 Erlangnode is running must have access to the file system (directly or throughNFS).
- The functions in the
binary
- Read operations on the file return binaries rather than lists.{delayed_write, Size, Delay}
- Data in subsequentwrite/2
calls is buffered until at leastSize
bytes are buffered, or until theoldest buffered data isDelay
milliseconds old. Then all buffered data iswritten in one operating system call. The buffered data is also flushed beforesome other file operation thanwrite/2
is executed.The purpose of this option is to increase performance by reducing the numberof operating system calls. Thus, the
write/2
calls must be forsizes significantly less thanSize
, and not interspersed by too many otherfile operations.When this option is used, the result of
write/2
calls canprematurely be reported as successful, and if a write error occurs, the erroris reported as the result of the next file operation, which is not executed.For example, when
delayed_write
is used, after a number ofwrite/2
calls,close/1
can return{error, enospc}
, as there is not enough space on the disc for previouslywritten data.close/1
must probably be called again, as thefile is still open.delayed_write
- The same as{delayed_write, Size, Delay}
withreasonable default values forSize
andDelay
(roughly some 64 KB, 2seconds).{read_ahead, Size}
- Activates read data buffering. Ifread/2
calls are for significantly less thanSize
bytes, readoperations to the operating system are still performed for blocks ofSize
bytes. The extra data is buffered and returned in subsequentread/2
calls, giving a performance gain as the number ofoperating system calls is reduced.The
read_ahead
buffer is also highly used by functionread_line/1
inraw
mode, therefore this option isrecommended (for performance reasons) when accessing raw files using thatfunction.If
read/2
calls are for sizes not significantly less than, oreven greater thanSize
bytes, no performance gain can be expected.read_ahead
- The same as{read_ahead, Size}
with a reasonable defaultvalue forSize
(roughly some 64 KB).compressed
- Makes it possible to read or write gzip compressed files.Optioncompressed
must be combined withread
orwrite
, but not both.Notice that the file size obtained withread_file_info/1
does probably notmatch the number of bytes that can be read from a compressed file.compressed_one
- Read one member of a gzip compressed file. Optioncompressed_one
can only be combined withread
.{encoding, Encoding}
- Makes the file perform automatic translation ofcharacters to and from a specific (Unicode) encoding. Notice that the datasupplied towrite/2
or returned byread/2
still is byte-oriented; thisoption denotes only how data is stored in the disk file.Depending on the encoding, different methods of reading and writing data ispreferred. The default encoding of
latin1
implies using this module (file
)for reading and writing data as the interfaces provided here work withbyte-oriented data. Using other (Unicode) encodings makes theio
functionsget_chars
,get_line
, andput_chars
more suitable, as they can work withthe full Unicode range.If data is sent to an
io_device/0
in a format that cannot be converted tothe specified encoding, or if data is read by a function that returns data ina format that cannot cope with the character range of the data, an erroroccurs and the file is closed.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 thefile, that is,read/2
are returned "as is". If moduleio
is used forwriting, the file can only cope with Unicode characters up to code point 255(the ISO Latin-1 range).unicode or utf8
- Characters are translated to and from UTF-8 encodingbefore they are written to or read from the file. A file opened in this waycan be readable using functionread/2
, as long as no data stored on thefile lies beyond the ISO Latin-1 range (0..255), but failure occurs if thedata contains Unicode code points beyond that range. The file is best readwith the functions in the Unicode aware moduleio
.Bytes written to the file by any means are translated to UTF-8 encodingbefore being stored on the disk file.
utf16 or {utf16,big}
- Works likeunicode
, but translation is doneto and from big endian UTF-16 instead of UTF-8.{utf16,little}
- Works likeunicode
, but translation is done to andfrom little endian UTF-16 instead of UTF-8.utf32 or {utf32,big}
- Works likeunicode
, but translation is doneto and from big endian UTF-32 instead of UTF-8.{utf32,little}
- Works likeunicode
, but translation is done to andfrom 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 beforefurther reading. For functions identifying BOMs, see moduleunicode
.This option is not allowed on
raw
files.ram
-File
must beiodata/0
. Returns anfd/0
, which letsmodulefile
operate on the data in-memory as if it is a file.sync
- On platforms supporting it, enables the POSIXO_SYNC
synchronous I/O flag or its platform-dependent equivalent (for example,FILE_FLAG_WRITE_THROUGH
on Windows) so that writes to the file block untilthe data is physically written to disk. However, be aware that the exactsemantics of this flag differ from platform to platform. For example, none ofLinux or Windows guarantees that all file metadata are also written before thecall returns. For precise semantics, check the details of your platformdocumentation. On platforms with no support for POSIXO_SYNC
or equivalent,use of thesync
flag causesopen
to return{error, enotsup}
.directory
- Allowsopen
to work on directories.
Returns:
{ok, IoDevice}
- The file is opened in the requested mode.IoDevice
isa reference to the file.{error, Reason}
- The file cannot be opened.
IoDevice
is really the pid of the process that handles the file. This processmonitors the process that originally opened the file (the owner process). If theowner process terminates, the file is closed and the process itself terminatestoo. AnIoDevice
returned from this call can be used as an argument to the I/Ofunctions (seeio
).
Warning
While this function can be used to open any file, we recommend against usingit for NFS-mounted files, FIFOs, devices, or similar since they can cause IOthreads to hang forever.
If your application needs to interact with these kinds of files we recommendbreaking out those parts to a port program instead.
Note
In previous versions offile
, modes were specified as one of the atomsread
,write
, orread_write
instead of a list. This is still allowed forreasons of backwards compatibility, but is not to be used for new code. Alsonote thatread_write
is 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 theparent directories.eisdir
- The named file is a directory.enotdir
- A component of the filename is not a directory, or thefilename itself is not a directory ifdirectory
mode was specified. On someplatforms,enoent
is returned instead.enospc
- There is no space left on the device (ifwrite
access wasspecified).
-spec 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 pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsErlang terms, separated by.
, from the file.
Returns one of the following:
{ok, Terms, FullName}
- The file is successfully read.FullName
is thefull 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 theErlang terms in the file. Useformat_error/1
to convert the three-elementtuple to an English description of the error.
The encoding ofFilename
can be set by a comment as described inepp
.
-spec 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 pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsand evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file. The result of evaluation isnot returned; any expression sequence in the file must be there for its sideeffect.
Returns one of the following:
{ok, FullName}
- The file is read and evaluated.FullName
is the fullname 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 theErlang expressions in the file. Useformat_error/1
to convert thethree-element tuple to an English description of the error.
The encoding ofFilename
can be set by a comment as described inepp
.
-spec 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.
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then opensthe file in the mode determined byModes
.
Returns one of the following:
{ok, IoDevice, FullName}
- The file is opened in the requested mode.IoDevice
is a reference to the file andFullName
is the full name of thefile.{error, enoent}
- The file cannot be found in any of the directories inPath
.{error, atom()}
- The file cannot be opened.
-spec 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()}.
Searches the pathPath
(a list of directory names) until the fileFilename
is found. IfFilename
is an absolute filename,Path
is ignored. Then readsand evaluates Erlang expressions, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file.
Returns one of the following:
{ok, Value, FullName}
- The file is read and evaluated.FullName
isthe full name of the file andValue
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 theErlang expressions in the file. Useformat_error/1
to convert thethree-element tuple to an English description of the error.
The encoding ofFilename
can be set by a comment as described inepp
.
-spec 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()}.
The same aspath_script/2
but the variable bindingsBindings
are used in the evaluation. Seeerl_eval
about variable bindings.
-spec position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason} when IoDevice ::io_device(), Location ::location(), NewPosition ::integer(), Reason ::posix() | badarg | terminated.
Sets the position of the file referenced byIoDevice
toLocation
. Returns{ok, NewPosition}
(as absolute offset) if successful, 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 withOffset
0.
Notice that offsets are counted in bytes, not in characters. If the file isopened using some otherencoding
thanlatin1
, one byte does not correspondto one character. Positioning in such a file can only be done to known characterboundaries. That is, to a position earlier retrieved by getting a currentposition, to the beginning/end of the file or to some other positionknown tobe on a correct character boundary by some other means (typically beyond a byteorder mark in the file, which has a known byte-size).
A typical error reason is:
einval
- EitherLocation
is illegal, or it is evaluated to a negativeoffset in the file. Notice that if the resulting position is a negative value,the result is an error, and after the call the file position is undefined.
-spec 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.
Performs a sequence ofpread/3
in one operation, which is moreefficient than calling them one at a time. Returns{ok, [Data, ...]}
or{error, Reason}
, where eachData
, the result of the correspondingpread
,is either a list or a binary depending on the mode of the file, oreof
if therequested position is beyond end of file.
As the position is specified as a byte-offset, take special caution when workingwith files whereencoding
is set to something else thanlatin1
, as not everybyte position is a valid character boundary on such a file.
-spec 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.
Combinesposition/2
andread/2
in one operation,which is more efficient than calling them one at a time.
Location
is only allowed to be an integer forraw
andram
modes.
The current position of the file after the operation is undefined forraw
modeand unchanged forram
mode.
As the position is specified as a byte-offset, take special caution when workingwith files whereencoding
is set to something else thanlatin1
, as not everybyte position is a valid character boundary on such a file.
-spec pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}} when IoDevice ::io_device(), LocBytes :: [{Location ::location(), Bytes ::iodata()}], N ::non_neg_integer(), Reason ::posix() | badarg | terminated.
Performs a sequence ofpwrite/3
in one operation, which is moreefficient than calling them one at a time. Returnsok
or{error, {N, Reason}}
, whereN
is the number of successful writes done beforethe failure.
When positioning in a file with otherencoding
thanlatin1
, caution must betaken to set the position on a correct character boundary. For details, seeposition/2
.
-spec pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason} when IoDevice ::io_device(), Location ::location(), Bytes ::iodata(), Reason ::posix() | badarg | terminated.
Combinesposition/2
andwrite/2
in oneoperation, which is more efficient than calling them one at a time.
Location
is only allowed to be an integer forraw
andram
modes.
The current position of the file after the operation is undefined forraw
modeand unchanged forram
mode.
When positioning in a file with otherencoding
thanlatin1
, caution must betaken to set the position on a correct character boundary. For details, seeposition/2
.
-spec 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}.
ReadsNumber
bytes/characters from the file referenced byIoDevice
.
The functionsread/2
,pread/3
, andread_line/1
are the only ways to read froma file opened inraw
mode (although they work for normally opened files, too).
For files whereencoding
is set to something else thanlatin1
, one charactercan be represented by more than one byte on the file. The parameterNumber
always denotes the number ofcharacters read from the file, while the positionin the file can be moved much more than this number when reading a Unicode file.
Also, ifencoding
is set to something else thanlatin1
, theread/2
call fails if the data contains characters larger than 255,which is whyio:get_chars/3
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 arereturned in a binary, otherwise in a list. The list or binary is shorter thanthe number of bytes requested if end of file was reached.eof
- Returned ifNumber>0
and end of file was reached before anythingat 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 anotherencoding
thanlatin1
and the data in the file cannot be translated to thebyte-oriented data that this function returns.
-spec read_file(Filename) -> {ok, Binary} | {error, Reason} when Filename ::name_all(), Binary ::binary(), Reason ::posix() | badarg | terminated | system_limit.
Equivalent toread_file(Filename, [])
.
-spec 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}
, whereBinary
is a binary data object that contains thecontents ofFilename
, or{error, Reason}
if an error occurs.
If the optionraw
is set, the file server is not called.
Typical error reasons:
enoent
- The file does not exist.eacces
- Missing permission for reading the file, or for searching oneof the parent directories.eisdir
- The named file is a directory.enotdir
- A component of the filename is not a directory. On someplatforms,enoent
is returned instead.enomem
- There is not enough memory for the contents of the file.
-spec read_file_info(File) -> {ok, FileInfo} | {error, Reason} when File ::name_all() |io_device(), FileInfo ::file_info(), Reason ::posix() | badarg.
Equivalent toread_file_info(File, [])
.
-spec 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}
.
FileInfo
is a recordfile_info
, defined in the Kernel include filefile.hrl
.Include the following directive in the module from which the function is called:
-include_lib("kernel/include/file.hrl").
The time type returned inatime
,mtime
, andctime
is dependent on the timetype set inOpts :: {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 optionraw
is set, the file server is not called and only informationabout local files is returned. Note that this will break this module's atomicityguarantees as it can race with a concurrent call towrite_file_info/1,2
.
This option has no effect when the function is given an I/O device instead of afile name. Useopen/2
with theraw
mode to obtain a file descriptor first.
Note
As file times are stored in POSIX time on most OS, it is faster to query fileinformation with optionposix
.
The recordfile_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. Canalso containsymlink
when returned fromread_link_info/1,2.access = read | write | read_write | none
- The current system access tothe file.atime =
date_time/0
|
non_neg_integer/0
- The last time the file wasread.mtime =
date_time/0
|
non_neg_integer/0
- The last time the file waswritten.ctime =
date_time/0
|
non_neg_integer/0
- The interpretation of thistime field depends on the operating system. On Unix, it is the last time thefile or theinode
was changed. In Windows, it is the create time.mode =
non_neg_integer/0
- The file permissions as the sum of the followingbit 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 always 1for file systems that have no concept of links).major_device =
non_neg_integer/0
- Identifies the file system where thefile is located. In Windows, the number indicates a drive as follows: 0 meansA:, 1 means B:, and so on.minor_device =
non_neg_integer/0
- Only valid for character devices onUnix. In all other cases, this field is zero.inode =
non_neg_integer/0
- Gives theinode
number. On non-Unix filesystems, this field is zero.uid =
non_neg_integer/0
- Indicates the owner of the file. On non-Unix filesystems, this field is zero.gid =
non_neg_integer/0
- Gives the group that the owner of the filebelongs to. On non-Unix file systems, this field is zero.
Typical error reasons:
eacces
- Missing search permission for one of the parent directories ofthe file.enoent
- The file does not exist.enotdir
- A component of the filename is not a directory. On someplatforms,enoent
is returned instead.
-spec 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 byIoDevice
.
Lines are defined to be delimited by the linefeed (LF,\n
) character, but anycarriage return (CR,\r
) followed by a newline is also treated as a single LFcharacter (the carriage return is silently ignored). The line is returnedincluding the LF, but excluding any CR immediately followed by an LF. Thisbehaviour is consistent with the behaviour ofio:get_line/2
. If end of file isreached without any LF ending the last line, a line with no trailing LF isreturned.
The function can be used on files opened inraw
mode. However, it isinefficient to use it onraw
files if the file is not opened with option{read_ahead, Size}
specified. Thus, combiningraw
and{read_ahead, Size}
is highly recommended when opening a text file for raw line-oriented reading.
Ifencoding
is set to something else thanlatin1
, theread_line/1
call fails if the data contains characters largerthan 255, whyio: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 trailingLF, 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 couldbe 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 anotherencoding
thanlatin1
and the data on the file cannot be translated to thebyte-oriented data that this function returns.
-spec read_link(Name) -> {ok, Filename} | {error, Reason} when Name ::name_all(), Filename ::filename(), Reason ::posix() | badarg.
Returns{ok, Filename}
ifName
refers to a symboliclink that is not a raw filename, or{error, Reason}
otherwise. On platformsthat do not support symbolic links, the return value is{error,enotsup}
.
Typical error reasons:
einval
-Name
does not refer to a symbolic link or the name of thefile 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.
-spec read_link_all(Name) -> {ok, Filename} | {error, Reason} when Name ::name_all(), Filename ::filename_all(), Reason ::posix() | badarg.
Returns{ok, Filename}
ifName
refers to a symbolic link or{error, Reason}
otherwise. On platforms that do not support symbolic links,the return value is{error,enotsup}
.
Notice thatFilename
can be either a list or a binary.
Typical error reasons:
einval
-Name
does not refer to a symbolic link.enoent
- The file does not exist.enotsup
- Symbolic links are not supported on this platform.
-spec read_link_info(Name) -> {ok, FileInfo} | {error, Reason} when Name ::name_all(), FileInfo ::file_info(), Reason ::posix() | badarg.
Equivalent toread_link_info(Name, [])
.
-spec read_link_info(Name, Opts) -> {ok, FileInfo} | {error, Reason} when Name ::name_all(), Opts :: [file_info_option()], FileInfo ::file_info(), Reason ::posix() | badarg.
Works likeread_file_info/1,2
except that ifName
is asymbolic link, information about the link is returned in thefile_info
recordand thetype
field of the record is set tosymlink
.
If the optionraw
is set, the file server is not called and only informationabout local files is returned. Note that this will break this module's atomicityguarantees as it can race with a concurrent call towrite_file_info/1,2
IfName
is not a symbolic link, this function returns the same result asread_file_info/1
. On platforms that do not supportsymbolic links, this function is always equivalent toread_file_info/1
.
-spec rename(Source, Destination) -> ok | {error, Reason} when Source ::name_all(), Destination ::name_all(), Reason ::posix() | badarg.
Tries to rename the fileSource
toDestination
. It can be used to move files(and directories) between directories, but it is not sufficient to specify thedestination only. The destination filename must also be specified. For example,ifbar
is a normal file andfoo
andbaz
are directories,rename("foo/bar", "baz")
returns an error, butrename("foo/bar", "baz/bar")
succeeds. Returnsok
if it issuccessful.
Note
Renaming of open files is not allowed on most platforms (seeeacces
below).
Typical error reasons:
eacces
- Missing read or write permissions for the parent directories ofSource
orDestination
. On some platforms, this error is given if eitherSource
orDestination
is open.eexist
-Destination
is not an empty directory. On some platforms,also given whenSource
andDestination
are not of the same type.einval
-Source
is a root directory, orDestination
is asubdirectory ofSource
.eisdir
-Destination
is a directory, butSource
is not.enoent
-Source
does not exist.enotdir
-Source
is a directory, butDestination
is not.exdev
-Source
andDestination
are on different file systems.
-spec 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, separated by.
(or,
, a sequence ofexpressions is also an expression), from the file.
Returns one of the following:
{ok, Value}
- The file is read and evaluated.Value
is the value ofthe last expression.{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 theErlang expressions in the file. Useformat_error/1
to convert thethree-element tuple to an English description of the error.
The encoding ofFilename
can be set by a comment as described inepp
.
-spec 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 asscript/1
but the variable bindingsBindings
areused in the evaluation. Seeerl_eval
about variable bindings.
-spec 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 fileFilename
toSocket
. Returns{ok, BytesSent}
if successful,otherwise{error, Reason}
.
-spec 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()].
SendsBytes
from the file referenced byRawFile
beginning atOffset
toSocket
. Returns{ok, BytesSent}
if successful, otherwise{error, Reason}
.IfBytes
is set to0
all data after the specifiedOffset
is sent.
The file used must be opened using theraw
flag, and the process callingsendfile
must be the controlling process of the socket. Seegen_tcp:controlling_process/2
or modulesocket
'slevelotp
socket optioncontrolling_process
.
If the OS used does not support non-blockingsendfile
, an Erlang fallbackusingread/2
andgen_tcp:send/2
is used.
The option list can contain the following options:
chunk_size
- The chunk size used by the Erlang fallback to send data. Ifusing the fallback, set this to a value that comfortably fits in the systemsmemory. Default is 20 MB.
-spec 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 toDir
. Returnsok
ifsuccessful.
The functions in the modulefile
usually treat binaries as raw filenames, thatis, they are passed "as is" even when the encoding of the binary does not agreewithnative_name_encoding()
. However, thisfunction expects binaries to be encoded according to the value returned bynative_name_encoding/0
.
Typical error reasons are:
enoent
- The directory does not exist.enotdir
- A component ofDir
is not a directory. On some platforms,enoent
is returned.eacces
- Missing permission for the directory or one of its parents.badarg
-Dir
has an improper type, such as tuple.no_translation
-Dir
is abinary/0
with characters coded inISO-latin-1 and the VM is operating with unicode filename encoding.
Warning
In a future release, a bad type for argumentDir
will probably generate anexception.
-spec 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 runtimesystem) are written to disk. On some platforms, this function might have noeffect.
A typical error reason is:
enospc
- Not enough space left to write the file.
-spec truncate(IoDevice) -> ok | {error, Reason} when IoDevice ::io_device(), Reason ::posix() | badarg | terminated.
Truncates the file referenced byIoDevice
at the current position. Returnsok
if successful, otherwise{error, Reason}
.
-spec write(IoDevice, Bytes) -> ok | {error, Reason} when IoDevice ::io_device() |io:device(), Bytes ::iodata(), Reason ::posix() | badarg | terminated.
WritesBytes
to the file referenced byIoDevice
. This function is the onlyway to write to a file opened inraw
mode (although it works for normallyopened files too). Returnsok
if successful, and{error, Reason}
otherwise.
If the file is opened withencoding
set to something else thanlatin1
, eachbyte written can result in many bytes being written to the file, as the byterange 0..255 can represent anything between one and four bytes depending onvalue and UTF encoding type. If you want to writeunicode:chardata/0
to theIoDevice
you should useio:put_chars/2
instead.
Typical error reasons:
ebadf
- The file is not opened for writing.enospc
- No space is left on the device.
-spec write_file(Filename, Bytes) -> ok | {error, Reason} when Filename ::name_all(), Bytes ::iodata(), Reason ::posix() | badarg | terminated | system_limit.
Writes the contents of theiodata
termBytes
to fileFilename
. The file iscreated if it does not exist. If it exists, the previous contents areoverwritten. Returnsok
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 someplatforms,enoent
is returned instead.enospc
- No space is left on the device.eacces
- Missing permission for writing the file or searching one of theparent directories.eisdir
- The named file is a directory.
-spec write_file(Filename, Bytes, Modes) -> ok | {error, Reason} when Filename ::name_all(), Bytes ::iodata(), Modes :: [mode()], Reason ::posix() | badarg | terminated | system_limit.
Same aswrite_file/2
, but takes a third argumentModes
, alist of possible modes, seeopen/2
. The mode flagsbinary
andwrite
areimplicit, so they are not to be used.
-spec write_file_info(Filename, FileInfo) -> ok | {error, Reason} when Filename ::name_all(), FileInfo ::file_info(), Reason ::posix() | badarg.
Equivalent towrite_file_info(Filename, FileInfo, [])
.
-spec write_file_info(Filename, FileInfo, Opts) -> ok | {error, Reason} when Filename ::name_all(), Opts :: [file_info_option()], FileInfo ::file_info(), Reason ::posix() | badarg.
Changes file information. Returnsok
if successful, otherwise{error, Reason}
.
FileInfo
is a recordfile_info
, defined in the Kernelinclude filefile.hrl
. Include the following directive in the module fromwhich the function is called:
-include_lib("kernel/include/file.hrl").
The time type set inatime
,mtime
, andctime
depends on the time type setinOpts :: {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 optionraw
is set, the file server is not called and only informationabout 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 wasread.mtime =
date_time/0
|
non_neg_integer/0
- The last time the file waswritten.ctime =
date_time/0
|
non_neg_integer/0
- On Unix, any valuespecified for this field is ignored (the "ctime" for the file is set to thecurrent time). On Windows, this field is the new creation time to set for thefile.mode =
non_neg_integer/0
- The file permissions as the sum of the followingbit 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-Unixfile 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 ofthe file.enoent
- The file does not exist.enotdir
- A component of the filename is not a directory. On someplatforms,enoent
is returned instead.