file

File Interface Module

The module file provides an interface to the file system.

file模块提供了一个文件系统接口.

On operating systems with thread support, it is possible to let file operations be performed in threads of their own, allowing other Erlang processes to continue executing in parallel with the file operations. See the command line flag +A in erl(1).

在支持线程的操作系统上, 可能会让文件操作在它们自己的线程上进行, 从而使得Erlang的进程能够与文件系统并行的执行. 参阅erl(1)中的命令行标记+A .

The Erlang VM supports file names in Unicode to a limited extent. Depending on how the VM is started (with the parameter +fnu or +fnl), file names given can contain characters > 255 and the VM system will convert file names back and forth to the native file name encoding.

Erlang的虚拟机支持Unicode编码的限制长度的文件名字. 这取决于虚拟机是如何启动的(以+fnu+fnl作为参数), 文件名可以包含多于255个字符并且虚拟机系统将会把文件名转换成本地文件名编码方式.

The default behavior for Unicode character translation depends on to what extent the underlying OS/filesystem enforces consistent naming. On OSes where all file names are ensured to be in one or another encoding, Unicode is the default (currently this holds for Windows and MacOSX). On OSes with completely transparent file naming (i.e. all Unixes except MacOSX), ISO-latin-1 file naming is the default. The reason for the ISO-latin-1 default is that file names are not guaranteed to be possible to interpret according to the Unicode encoding expected (i.e. UTF-8), and file names that cannot be decoded will only be accessible by using "raw file names", in other word file names given as binaries.

Unicode字符转换的默认行为取决于底层系统或文件系统对文件名长度的限制. 在那些所有文件名确定可以是一个或其它编码系统的系统上, Unicode编码是默认的(目前Windows和MacOSX是这样的). 在文件名是完全透明的系统上(例如除了MacOSX以外所有Unix系统), ISO-latin-1的文件名编码是默认的. 使用ISO-latin-1作为默认编码的原因是文件名不能保证可以根据所期望的Unicode编码(例如UTF-8)进行解释, 并且那写不能解码的文件名将只能会通过使用"原始文件名", 也就是说文件名以二进制的形式给出.

As file names are traditionally not binaries in Erlang, applications that need to handle raw file names need to be converted, why the Unicode mode for file names is not default on systems having completely transparent file naming.

因为在Erlang中文件名通常不是二进制形式, 所以在处理原始文件名的应用中需要进行转换, 这也就是为什么在拥有完全透明的文件名的系统上Unicode模式的文件名不是默认的原因.

Note:

As of R14B01, the most basic file handling modules (file, prim_file, filelib and filename) accept raw file names, but the rest of OTP is not guaranteed to handle them, why Unicode file naming on systems where it is not default is still considered experimental.

在R14B01中, 最基本的文件处理模块(file, prim_file, filelibfilename) 都能够接受原始文件名, 但是不能保证OTP其他部分也能处理它们, 这就是为什么Unicode编码的文件名在[TODO] 系统why Unicode file naming on systems where it is not default is still considered experimental.

Raw file names is a new feature in OTP R14B01, which allows the user to supply completely uninterpreted file names to the underlying OS/filesystem. They are supplied as binaries, where it is up to the user to supply a correct encoding for the environment. The function file:native_name_encoding() can be used to check what encoding the VM is working in. If the function returns latin1 file names are not in any way converted to Unicode, if it is utf8, raw file names should be encoded as UTF-8 if they are to follow the convention of the VM (and usually the convention of the OS as well). Using raw file names is useful if you have a filesystem with inconsistent file naming, where some files are named in UTF-8 encoding while others are not. A file:list_dir on such mixed file name systems when the VM is in Unicode file name mode might return file names as raw binaries as they cannot be interpreted as Unicode file names. Raw file names can also be used to give UTF-8 encoded file names even though the VM is not started in Unicode file name translation mode.

原始文件名是R14B01的一个新特性,这样就允许用户给底层的系统或文件系统提供根本未被翻译的文件名. 它们被以二进制的形式提供, [TODO]根据用户为环境提供正确的编码方式. 函数file:native_name_encoding()可以用来检测虚拟机是工作在什么编码环境下. 如果该函数返回latin1, 文件名将不会被以任何方式转换成Unicode, 如果返回utf8, 那么原始文件名应该被编码成UTF-8 be encoded as UTF-8 if they are to follow the convention of the VM (and usually the convention of the OS as well). Using raw file names is useful if you have a filesystem with inconsistent file naming, where some files are named in UTF-8 encoding while others are not. A file:list_dir on such mixed file name systems when the VM is in Unicode file name mode might return file names as raw binaries as they cannot be interpreted as Unicode file names. Raw file names can also be used to give UTF-8 encoded file names even though the VM is not started in Unicode file name translation mode.

Note that on Windows, file:native_name_encoding() returns utf8 per default, which is the format for raw file names even on Windows, although the underlying OS specific code works in a limited version of little endian UTF16. As far as the Erlang programmer is concerned, Windows native Unicode format is UTF-8...

注意在Windows系统上, file:native_name_encoding() 默认返回utf8, 即便原始文件名格式是在Windows系统上 , 尽管底层的操作系统特有代码在一个限制的小端UTF16的版本. As far as the Erlang programmer is concerned, Windows native Unicode format is UTF-8...

As returned by file:open/2, a process handling IO protocols.

If VM is in Unicode filename mode, string() and char() 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 filesystem (i.e. non-UTF-8 characters although the VM is started in Unicode filename mode).

An atom which is named from the POSIX error codes used in Unix, and in the runtime libraries of most C compilers.

Must denote a valid date and time.

Functions:


advise(IoDevice, Offset, Length, Advise) -> ok | {error, Reason}

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.

advise/4可以用来预示一个通过某种模式访问文件数据的意向,使得操作系统进行适当的优化.

On some platforms, this function might have no effect.

在某些平台这个函数可能没有效果.

change_group(Filename, Gid) -> ok | {error, Reason}

Filename = name(),
Gid = integer(),
Reason = posix() | badarg

Changes group of a file. See write_file_info/2.

更改文件的所属组. 参阅 write_file_info/2.

change_mode(Filename, Mode) -> ok | {error, Reason}

Filename = name(),
Mode = integer(),
Reason = posix() | badarg

Changes permissions of a file. See write_file_info/2.

更改文件权限. 参阅 write_file_info/2.

change_owner(Filename, Uid) -> ok | {error, Reason}

Filename = name(),
Uid = integer(),
Reason = posix() | badarg

Changes owner of a file. See write_file_info/2.

更改文件的所有者. 参阅 write_file_info/2.

change_owner(Filename, Uid, Gid) -> ok | {error, Reason}

Filename = name(),
Uid = integer(),
Gid = integer(),
Reason = posix() | badarg

Changes owner and group of a file. See write_file_info/2.

更改文件的所有者和所有组. 参阅 write_file_info/2.

change_time(Filename, Mtime) -> ok | {error, Reason}

Filename = name(),
Mtime = date_time(),
Reason = posix() | badarg

Changes the modification and access times of a file. See write_file_info/2.

更改文件的修改和访问时间. 参阅 write_file_info/2.

change_time(Filename, Atime, Mtime) -> ok | {error, Reason}

Filename = name(),
Atime = date_time(),
Mtime = date_time(),
Reason = posix() | badarg

Changes the modification and last access times of a file. See write_file_info/2.

更改文件的修改和访问时间. 参阅 write_file_info/2.

close(IoDevice) -> ok | {error, Reason}

IoDevice = io_device(),
Reason = posix() | badarg | terminated

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

关闭IoDevice引用的文件. 这通常会返回ok, 除非发生像超出内存这样的服务器错误.

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

注意,如果在打开文件的时候使用了delayed_write 选项, close/1 可能返回一个过时写错误,甚至不会尝试关闭这个文件. 参阅 open/2.

consult(Filename) -> {ok, Terms} | {error, Reason}

Filename = name(),
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:

Filename中读取用'.'分隔的Erlang项. 返回下列其中一种:

{ok, Terms}

The file was successfully read.

成功读取文件.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

当打开或读文件的时候发生一个错误. 参阅 open/2 中的典型错误代码.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang terms in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

当翻译文件中的Erlang项时发生一个错误. 使用format_error/1来将三元素的元组翻译成错误的英文描述.

Example:

示例:

f.txt:  {person, "kalle", 25}.
        {person, "pelle", 30}.
1> file:consult("f.txt").
{ok,[{person,"kalle",25},{person,"pelle",30}]}

copy(Source, Destination) -> {ok, BytesCopied} | {error, Reason}

Source = io_device() | Filename | {Filename, Modes},
Destination = io_device() | Filename | {Filename, Modes},
Filename = name(),
Modes = [mode()],
BytesCopied = non_neg_integer(),
Reason = posix() | badarg | terminated

copy(Source, Destination, ByteCount) -> {ok, BytesCopied} | {error, Reason}

Source = io_device() | Filename | {Filename, Modes},
Destination = io_device() | Filename | {Filename, Modes},
Filename = name(),
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 e.g. open/2. ByteCount defaults to infinity, denoting an infinite number of bytes.

SourceDestination拷贝ByteCount字节. SourceDestination 指向文件名或IO设备(例如open/2返回的IO). ByteCount 默认值 infinity, 代表无限字节.

The argument Modes is a list of possible modes, see open/2, and defaults to [].

参数Modes 是一个模式列表, 参阅 open/2, 默认值为[].

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.

如果SourceDestination 都是文件名, 那么这些文件将会分别以[read, binary][write, binary] 作为模式列表的前缀来优化拷贝.

If Source refers to a filename, it is opened with read mode prepended to the mode list before the copy, and closed when done.

如果 Source 是一个文件名, 那么它会在拷贝之前以read作为模式列表的前缀打开, 并且在结束的时候关闭.

If Destination refers to a filename, it is opened with write mode prepended to the mode list before the copy, and closed when done.

如果 Destination 是一个文件名, 那么它会在拷贝之前以write作为模式列表的前缀打开, 并且在结束的时候关闭.

Returns {ok, BytesCopied} where BytesCopied is the number of bytes that actually was copied, which may be less than ByteCount if end of file was encountered on the source. If the operation fails, {error, Reason} is returned.

返回 {ok, BytesCopied} 其中BytesCopied 是实际拷贝的字节数,如果遇到了文件结束符可能会小于ByteCount. 如果操作失败返回 {error, Reason}.

Typical error reasons: As for open/2 if a file had to be opened, and as for read/2 and write/2.

典型的错误原因: 如果需要打开文件时参阅open/2 , 以及read/2write/2.

del_dir(Dir) -> ok | {error, Reason}

Dir = name(),
Reason = posix() | badarg

Tries to delete the directory Dir. The directory must be empty before it can be deleted. Returns ok if successful.

尝试删除文件夹Dir.删除之前文件夹必须为空. 如果删除成功返回ok.

Typical error reasons are:

典型的错误原因:

eacces

Missing search or write permissions for the parent directories of Dir.

缺少对Dir父文件夹的搜索和写权限.

eexist

The directory is not empty.

文件夹不为空.

enoent

The directory does not exist.

文件夹不存在.

enotdir

A component of Dir is not a directory. On some platforms, enoent is returned instead.

Dir路径中存在不是文件夹的部分. 在某些平台, 返回的是enoent.

einval

Attempt to delete the current directory. On some platforms, eacces is returned instead.

试图删除当前文件夹. 在某些平台上, 返回的是eacces.

delete(Filename) -> ok | {error, Reason}

Filename = name(),
Reason = posix() | badarg

Tries to delete the file Filename. Returns ok if successful.

尝试删除文件Filename.如果成功, 返回ok.

Typical error reasons are:

典型的错误原因:

enoent

The file does not exist.

文件不存在.

eacces

Missing permission for the file or one of its parents.

缺失该文件或者它其中一个父文件夹的权限.

eperm

The file is a directory and the user is not super-user.

该文件是一个文件夹并且用户不是超级用户.

enotdir

A component of the file name is not a directory. On some platforms, enoent is returned instead.

文件路径中有部分不是文件夹. 在某些平台上, 返回的是enoent.

einval

Filename had an improper type, such as tuple.

Filename类型不正确, 例如元组.

Warning:

In a future release, a bad type for the Filename argument will probably generate an exception.

在以后的版本中, Filename的类型错误问题可能会产生一个异常.

eval(Filename) -> ok | {error, Reason}

Filename = name(),
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 actual 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:

Filename读取并且计算Erlang表达式, separated by '.' (or ',', a sequence of expressions is also an expression), from . 实际的计算结果并不返回; 并且任何any expression sequence in the file must be there for its side effect. 返回下列之一:

ok

The file was read and evaluated.

文件被读取并计算.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

在打开或读取文件的时候遇到一个错误. 参阅 open/2 中的典型错误代码.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang expressions in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

在解释文件中的Erlang表达式时遇到一个错误. 使用 format_error/1 函数将三元素元组转换成错误的英文描述信息.

eval(Filename, Bindings) -> ok | {error, Reason}

Filename = name(),
Bindings = erl_eval:binding_struct(),
Reason = posix() | badarg | terminated | system_limit
| {Line = integer(), Mod = module(), Term = term()}

The same as eval/1 but the variable bindings Bindings are used in the evaluation. See erl_eval(3) about variable bindings.

除了在计算过程中使用变量绑定Bindings 以外与eval/1相同. 参阅 erl_eval(3) 中关于变量绑定的内容.

file_info(Filename) -> {ok, FileInfo} | {error, Reason}

This function is obsolete. Use read_file_info/1,2 instead.

该函数已过时. 请使用read_file_info/1,2.

format_error(Reason) -> Chars

Reason = posix() | badarg | terminated | system_limit
| {Line = integer(), Mod = module(), Term = term()},
Chars = string()

Given the error reason returned by any function in this module, returns a descriptive string of the error in English.

给定一个由本模块任何一个函数返回的错误原因, 返回该错误的英文描述字符串.

get_cwd() -> {ok, Dir} | {error, Reason}

Dir = filename(),
Reason = posix()

Returns {ok, Dir}, where Dir is the current working directory of the file server.

返回 {ok, Dir}, 其中 Dir是文件服务器的当前工作目录.

Note:

In rare circumstances, this function can fail on Unix. It may happen if read permission does not exist for the parent directories of the current directory.

特殊环境下, 该函数在Unix系统上会失败. 这可能发生在没有当前文件夹路径上父文件夹的读权限时.

Typical error reasons are:

典型的错误原因:

eacces

Missing read permission for one of the parents of the current directory.

缺失当前文件夹路径上某个父文件夹的读权限.

get_cwd(Drive) -> {ok, Dir} | {error, Reason}

Drive = string(),
Dir = filename(),
Reason = posix() | badarg

Drive should be of the form "Letter:", for example "c:". Returns {ok, Dir} or {error, Reason}, where Dir is the current working directory of the drive specified.

Drive 应该是"Letter:"的形式, 例如"c:". 返回 {ok, Dir}{error, Reason}, 其中 Dir 是指定分区上的当前工作目录.

This function returns {error, enotsup} on platforms which have no concept of current drive (Unix, for example).

该函数在没有当前分区概念的平台(例如Unix)上返回{error, enotsup}.

Typical error reasons are:

典型的错误原因:

enotsup

The operating system has no concept of drives.

当前操作系统没有分区的概念.

eacces

The drive does not exist.

分区不存在.

einval

The format of Drive is invalid.

Drive格式不合法.

list_dir(Dir) -> {ok, Filenames} | {error, Reason}

Dir = name(),
Filenames = [filename()],
Reason = posix() | badarg

Lists all the files in a directory. Returns {ok, Filenames} if successful. Otherwise, it returns {error, Reason}. Filenames is a list of the names of all the files in the directory. The names are not sorted.

列出文件夹下的所有文件. 如果成功, 返回{ok, Filenames}. 否则, 返回{error, Reason}. Filenames 是一个包含文件夹中所有文件名的列表. 这些名字没有排序.

Typical error reasons are:

典型的错误原因:

eacces

Missing search or write permissions for Dir or one of its parent directories.

缺失Dir某个父文件夹的搜索或写权限.

enoent

The directory does not exist.

文件夹不存在.

make_dir(Dir) -> ok | {error, Reason}

Dir = name(),
Reason = posix() | badarg

Tries to create the directory Dir. Missing parent directories are not created. Returns ok if successful.

尝试创建文件夹Dir. 缺失父文件夹时创建文件夹. 如果成功, 返回ok.

Typical error reasons are:

典型的错误原因:

eacces

Missing search or write permissions for the parent directories of Dir.

缺失Dir某些父文件夹的搜索或写权限.

eexist

There is already a file or directory named Dir.

已存在一个以Dir命名的文件或文件夹.

enoent

A component of Dir does not exist.

Dir路径名中某部分不存在.

enospc

There is a no space left on the device.

空间不足.

enotdir

A component of Dir is not a directory. On some platforms, enoent is returned instead.

Dir路径名中某部分不是文件夹. 在某些平台上返回的是enoent.

make_link(Existing, New) -> ok | {error, Reason}

Existing = name(),
New = name(),
Reason = posix() | badarg

Makes a hard link from Existing to New, on platforms that support links (Unix and Windows). This function returns ok if the link was successfully created, or {error, Reason}. On platforms that do not support links, {error,enotsup} is returned.

在支持链接的平台上(例如unix, windows)创建一个从ExistingNew的硬链接. 如果链接创建成功返回 ok, 否则返回 {error, Reason}. 在不支持链接的平台上, 返回{error,enotsup} .

Typical error reasons:

典型的错误原因:

eacces

Missing read or write permissions for the parent directories of Existing or New.

缺失ExistingNew父文件夹的读或写权限.

eexist

New already exists.

New已存在.

enotsup

Hard links are not supported on this platform.

当前平台不支持硬链接.

make_symlink(Existing, New) -> ok | {error, Reason}

Existing = name(),
New = name(),
Reason = posix() | badarg

This function creates a symbolic link New to the file or directory Existing, on platforms that support symbolic links (most Unix systems and Windows beginning with Vista). Existing need not exist. This function returns ok if the link was successfully created, or {error, Reason}. On platforms that do not support symbolic links, {error, enotsup} is returned.

在支持符号链接的平台上(例如unix, Vista之后的windows)创建一个从ExistingNew的符号链接. Existing不必一定存在. 如果创建成功返回 ok, 否则返回 {error, Reason}. 在不支持符号链接的平台上, 返回{error,enotsup} .

Typical error reasons:

典型的错误原因:

eacces

Missing read or write permissions for the parent directories of Existing or New.

缺失ExistingNew父文件夹的读或写权限.

eexist

New already exists.

New 已存在.

enotsup

Symbolic links are not supported on this platform.

当前平台不支持符号链接.

native_name_encoding() -> latin1 | utf8

This function returns the configured default file name encoding to use for raw file names. Generally an application supplying file names raw (as binaries), should obey the character encoding returned by this function.

By default, the VM uses ISO-latin-1 file name encoding on filesystems and/or OSes that use completely transparent file naming. This includes all Unix versions except MacOSX, where the vfs layer enforces UTF-8 file naming. By giving the experimental option +fnu when starting Erlang, UTF-8 translation of file names can be turned on even for those systems. If Unicode file name translation is in effect, the system behaves as usual as long as file names conform to the encoding, but will return file names that are not properly encoded in UTF-8 as raw file names (i.e. binaries).

On Windows, this function also returns utf8 by default. The OS uses a pure Unicode naming scheme and file names are always possible to interpret as valid Unicode. The fact that the underlying Windows OS actually encodes file names using little endian UTF-16 can be ignored by the Erlang programmer. Windows and MacOSX are the only operating systems where the VM operates in Unicode file name mode by default.

open(Filename, Modes) -> {ok, IoDevice} | {error, Reason}

Filename = name(),
Modes = [mode()],
IoDevice = io_device(),
Reason = posix() | badarg | system_limit

Opens the file Filename in the mode determined by Modes, which may contain one or more of the following items:

以由Modes确定的模式打开文件Filename, 这些模式可以包含下述一个或多个项:

read

The file, which must exist, is opened for reading.

打开已存在的文件来进行读操作.

write

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

打开文件来进行写操作. 如果文件不存在,创建一个新文件. 如果文件存在, 并且write 不和read一起使用时, 文件将被截断(清空).

append

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

打开文件来进行写操作, 如果文件不存在则创建新文件. 当写以append模式打开的文件时, 写操作发生在文件的结尾.

exclusive

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

当打开来进行写操作的文件不存在时,创建一个新文件. 如果文件存在, open返回 {error, eexist}.

Warning:

This option does not guarantee exclusiveness on file systems that do not support O_EXCL properly, such as NFS. Do not depend on this option unless you know that the file system supports it (in general, local file systems should be safe).

在像NFS这样不能很好的支持O_EXCL的文件系统上,该选项不能确保排它性的实现. 除非你知道当前的文件系统支持这个选项(通常本地文件系统是安全支持的),否则不要依赖它.

raw

The raw option allows faster access to a file, because no Erlang process is needed to handle the file. However, a file opened in this way has the following limitations:

raw选项可以使文件的访问更快, 因为这样在处理文件的时候不再需要Erlang的进程. 然而,用这种方式打开的文件有下列限制:

The functions in the io module cannot be used, because they can only talk to an Erlang process. Instead, use the read/2, read_line/1 and write/2 functions.

不能使用io模块中的函数, 因为这些函数只能和Erlang进程通信. 作为代替, 可以使用read/2, read_line/1 以及 write/2 函数.

Especially if read_line/1 is to be used on a raw file, it is recommended to combine this option with the {read_ahead, Size} option as line oriented I/O is inefficient without buffering.

特别是 if read_line/1 is to be used on a raw file, it is recommended to combine this option with the {read_ahead, Size} option as line oriented I/O is inefficient without buffering.

Only the Erlang process which opened the file can use it.

只能由打开文件的进程使用这个文件.

A remote Erlang file server cannot be used; the computer on which the Erlang node is running must have access to the file system (directly or through NFS).

不能使用远程的Erlang文件系统; 运行Erlang节点的计算机必须直接或者通过NFS访问该文件系统.

binary

When this option has been given, read operations on the file will return binaries rather than lists.

当给定这个选项时, 对文件的读操作将会返回二进制串而不是列表.

{delayed_write, Size, Delay}

If this option is used, the data in subsequent write/2 calls is buffered until there are at least Size bytes buffered, or until the oldest buffered data is Delay milliseconds old. Then all buffered data is written in one operating system call. The buffered data is also flushed before some other file operation than write/2 is executed.

如果使用这个选项, 那么后续write/2函数调用中的数据将会在达到或者超过Size字节之前一直被缓存,或者最早的缓存数据已经超过了Delay毫秒. 之后,所有缓存的数据将会通过一次系统函数调用写入. 缓冲数据也在除了write/2以外的文件操作执行之前被冲刷.

The purpose of this option is to increase performance by reducing the number of operating system calls, so the write/2 calls should be for sizes significantly less than Size, and not interspersed by to many other file operations, for this to happen.

这个选项的目的是通过减少系统调用的次数来提高性能 为了能达到这个效果, write/2 函数调用应该适用于远小于Size的数据, 并且不能穿插在其他文件操作当中.

When this option is used, the result of write/2 calls may prematurely be reported as successful, and if a write error should actually occur the error is reported as the result of the next file operation, which is not executed.

当使用这个选项的时候, write/2马上返回成功的返回结果,如果遇到一个写时错误,那么将延迟到下次文件操作时报错(报错时的文件操作没有执行).

For example, when delayed_write is used, after a number of write/2 calls, close/1 might return {error, enospc} because there was not enough space on the disc for previously written data, and close/1 should probably be called again since the file is still open.

例如, 当使用delayed_write时, 在一系列的write/2的调用之后, close/1 可能返回{error, enospc} 这是因为没有足够的磁盘空间分配给之前写入的数据, 而且应该再次调用close/1函数来关闭仍处于打开状态的文件.

delayed_write

The same as {delayed_write, Size, Delay} with reasonable default values for Size and Delay. (Roughly some 64 KBytes, 2 seconds)

等同于拥有SizeDelay默认值(大约是64字节, 2秒钟)的{delayed_write, Size, Delay}.

{read_ahead, Size}

This option activates read data buffering. If read/2 calls are for significantly less than Size bytes, read operations towards the operating system are still performed for blocks of Size bytes. The extra data is buffered and returned in subsequent read/2 calls, giving a performance gain since the number of operating system calls is reduced.

该选项激活了读操作数据缓冲区. read/2函数调用是针对于远小于Size字节的数据, 面向操作系统的读操作仍然操作于Size字节大小的数据块. 额外的数据被缓冲下来待下次read/2调用时返回, 这样就通过减少了系统调用次数而获得性能的提高.

The read_ahead buffer is also highly utilized by the read_line/1 function in raw mode, why this option is recommended (for performance reasons) when accessing raw files using that function.

The read_ahead buffer is also highly utilized by the read_line/1 function in raw mode, why this option is recommended (for performance reasons) when accessing raw files using that function.

If read/2 calls are for sizes not significantly less than, or even greater than Size bytes, no performance gain can be expected.

如果read/2函数调用的数据并不远小于, 或者大于Size字节, 那么将不能获得预期的高性能.

read_ahead

The same as {read_ahead, Size} with a reasonable default value for Size. (Roughly some 64 KBytes)

除了Size拥有一个合理的默认值(大概是64KB), 与{read_ahead, Size}相同.

compressed

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

使读或写gzip压缩文件成为可能. compressed 选项必须和readwrite其中之一一起使用. 注意, 通过read_file_info/1函数调用获得的文件大小可能与可读的压缩文件字节数目不匹配.

{encoding, Encoding}

Makes the file perform automatic translation of characters to and from a specific (Unicode) encoding. Note that the data supplied to file:write or returned by file:read still is byte oriented, this option only denotes how data is actually stored in the disk file.

Depending on the encoding, different methods of reading and writing data is preferred. The default encoding of latin1 implies using this (the file) module for reading and writing data, as the interfaces provided here work with byte-oriented data, while using other (Unicode) encodings makes the io(3) module's get_chars, get_line and put_chars functions more suitable, as they can work with the full Unicode range.

If data is sent to an io_device() in a format that cannot be converted to the specified encoding, or if data is read by a function that returns data in a format that cannot cope with the character range of the data, an error occurs and the file will be closed.

The allowed values for Encoding are:

Encoding的可用值:

latin1

The default encoding. Bytes supplied to i.e. file:write are written as is on the file, likewise bytes read from the file are returned to i.e. file:read as is. If the io(3) module is used for writing, the file can only cope with Unicode characters up to codepoint 255 (the ISO-latin-1 range).

unicode or utf8

Characters are translated to and from the UTF-8 encoding before being written to or read from the file. A file opened in this way might be readable using the file:read function, as long as no data stored on the file lies beyond the ISO-latin-1 range (0..255), but failure will occur if the data contains Unicode codepoints beyond that range. The file is best read with the functions in the Unicode aware io(3) module.

Bytes written to the file by any means are translated to UTF-8 encoding before actually being stored on the disk file.

utf16 or {utf16,big}

Works like unicode, but translation is done to and from big endian UTF-16 instead of UTF-8.

{utf16,little}

Works like unicode, but translation is done to and from little endian UTF-16 instead of UTF-8.

utf32 or {utf32,big}

Works like unicode, but translation is done to and from big endian UTF-32 instead of UTF-8.

{utf32,little}

Works like unicode, 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 the io:setopts/2 function, why a file can be analyzed in latin1 encoding for i.e. a BOM, positioned beyond the BOM and then be set for the right encoding before further reading.See the unicode(3) module for functions identifying BOM's.

This option is not allowed on raw files.

Returns:

返回值:

{ok, IoDevice}

The file has been opened in the requested mode. IoDevice is a reference to the file.

文件已经按照要求的模式打开. IoDevice是该文件的一个引用.

{error, Reason}

The file could not be opened.

不能打开文件.

IoDevice is really the pid of the process which handles the file. This process is linked to the process which originally opened the file. If any process to which the IoDevice is linked terminates, the file will be closed and the process itself will be terminated. An IoDevice returned from this call can be used as an argument to the IO functions (see io(3)).

IoDevice 是处理文件的进程号. 该进程与最初打开文件的进程相链接. 如果IoDevice链接的任意一个进程终止,那么文件将被关闭而该进程也会被终止. 由该函数调用返回的 IoDevice 可以作为IO函数的参数(参阅 io(3)).

Note:

In previous versions of file, modes were given as one of the atoms read, write, or read_write instead of a list. This is still allowed for reasons of backwards compatibility, but should not be used for new code. Also note that read_write is not allowed in a mode list.

file之前的版本中, 模式是通过给定read, write, 或者 read_write其中一个原子而不是一个列表指出的. 出于向后兼容的原因,仍然可以使用这种方式,但是对于新代码就不应该使用了. 同时也请注意read_write不能出现在模式列表中.

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 not a regular file. It may be a directory, a fifo, or a device.

该命名的文件不是一个普通文件. 它可能是一个目录,一个FIFO管道文件,或者一个设备

enotdir

A component of the file name is not a directory. On some platforms, enoent is returned instead.

文件路径的某个组成部分不是文件夹. 在某些平台上, 返回的是enoent.

enospc

There is a no space left on the device (if write access was specified).

空间不足(如果指定了write访问).

path_consult(Path, Filename) -> {ok, Terms, FullName} | {error, Reason}

Path = [Dir],
Dir = name(),
Filename = name(),
Terms = [term()],
FullName = filename(),
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:

搜索路径Path (一个文件夹路径列表) 直到发现Filename文件. 如果Filename是一个绝对路径, 那么将会忽略Path. 之后从文件中读取以'.'分隔的Erlang项. 返回下列之一:

{ok, Terms, FullName}

The file was successfully read. FullName is the full name of the file.

成功读取文件. FullName是文件的完整路径名.

{error, enoent}

The file could not be found in any of the directories in Path.

列表Path里所有的文件夹中都未找到目标文件.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

在打开或者读取文件的时候发生一个错误. 参阅 open/2 中的典型错误代码列表.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang terms in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

当翻译文件中的Erlang项时发生一个错误. 使用format_error/1来将三元素的元组翻译成错误的英文描述.

path_eval(Path, Filename) -> {ok, FullName} | {error, Reason}

Path = [Dir = name()],
Filename = name(),
FullName = filename(),
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 file name, Path is ignored. Then reads and evaluates Erlang expressions, separated by '.' (or ',', a sequence of expressions is also an expression), from the file. The actual result of evaluation is not returned; any expression sequence in the file must be there for its side effect. Returns one of the following:

搜索路径Path (一个文件夹路径列表) 直到发现Filename文件. 如果Filename是一个绝对路径, 那么将会忽略Path. Then reads and evaluates Erlang expressions, separated by '.' (or ',', a sequence of expressions is also an expression), from the file. The actual result of evaluation is not returned; any expression sequence in the file must be there for its side effect. Returns one of the following:

{ok, FullName}

The file was read and evaluated. FullName 是完整的文件路径.

读取并求值. FullName 是文件的完整路径名.

{error, enoent}

The file could not be found in any of the directories in Path.

列表Path里所有的文件夹中都未找到目标文件.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

在打开或者读取文件的时候发生一个错误. 参阅 open/2 中的典型错误代码列表.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang expressions in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

当翻译文件中的Erlang项时发生一个错误. 使用format_error/1来将三元素的元组翻译成错误的英文描述.

path_open(Path, Filename, Modes) -> {ok, IoDevice, FullName} | {error, Reason}

Path = [Dir = name()],
Filename = name(),
Modes = [mode()],
IoDevice = io_device(),
FullName = filename(),
Reason = posix() | badarg | system_limit

Searches the path Path (a list of directory names) until the file Filename is found. If Filename is an absolute file name, Path is ignored. Then opens the file in the mode determined by Modes. Returns one of the following:

搜索路径Path (一个文件夹路径列表) 直到发现Filename文件. 如果Filename是一个绝对路径, 那么将会忽略Path. 之后以Modes确定的模式打开文件. 返回下列之一:

{ok, IoDevice, FullName}

The file has been opened in the requested mode. IoDevice is a reference to the file and FullName is the full name of the file.

文件以所需的模式打开. IoDevice 文件的一个引用, FullName 是文件的完整路径.

{error, enoent}

The file could not be found in any of the directories in Path.

列表Path里所有的文件夹中都未找到目标文件.

{error, atom()}

The file could not be opened.

无法打开文件.

path_script(Path, Filename) -> {ok, Value, FullName} | {error, Reason}

Path = [Dir = name()],
Filename = name(),
Value = term(),
FullName = filename(),
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 file name, Path is ignored. Then reads and evaluates Erlang expressions, separated by '.' (or ',', a sequence of expressions is also an expression), from the file. Returns one of the following:

{ok, Value, FullName}

The file was read and evaluated. FullName is the full name of the file and Value the value of the last expression.

读取文件并求值. FullName is the full name of the file and Value the value of the last expression.

{error, enoent}

The file could not be found in any of the directories in Path.

列表Path里所有的文件夹中都未找到目标文件.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

在打开或者读取文件的时候发生一个错误. 参阅 open/2 中的典型错误代码列表.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang expressions in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

当翻译文件中的Erlang项时发生一个错误. 使用format_error/1来将三元素的元组翻译成错误的英文描述.

path_script(Path, Filename, Bindings) -> {ok, Value, FullName} | {error, Reason}

Path = [Dir = name()],
Filename = name(),
Bindings = erl_eval:binding_struct(),
Value = term(),
FullName = filename(),
Reason = posix() | badarg | terminated | system_limit
| {Line = integer(), Mod = module(), Term = term()}

The same as path_script/2 but the variable bindings Bindings are used in the evaluation. See erl_eval(3) about variable bindings.

pid2name(Pid) -> {ok, Filename} | undefined

Filename = filename(),
Pid = pid()

If Pid is an IO device, that is, a pid returned from open/2, this function returns the filename, or rather:

如果Pid 是一个IO设备, 也就是说该进程号是由open/2返回的, 该函数返回相应的文件名, 更确切的是:

{ok, Filename}

If this node's file server is not a slave, the file was opened by this node's file server, (this implies that Pid must be a local pid) and the file is not closed. Filename is the filename in flat string format.

如果该节点的文件服务器不是"slave", 文件由该节点的文件服务器打开, (暗指Pid 必须是本地进程号) 并且文件没有关闭. Filename 是平坦化的字符串文件名.

undefined

In all other cases.

其它情况.

Warning:

This function is intended for debugging only.

设计该函数只是用于调试.

position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason}

IoDevice = io_device(),
Location = location(),
NewPosition = integer(),
Reason = posix() | badarg | terminated

Sets the position of the file referenced by IoDevice to Location. Returns {ok, NewPosition} (as absolute offset) if successful, otherwise {error, Reason}. Location is one of the following:

设置IoDevice引用的文件指针位置为Location. 如果成功的话返回{ok, NewPosition} (绝对文件偏移量), 否则返回{error, Reason}. Location为下列之一:

Offset

The same as {bof, Offset}.

等同于{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 with Offset 0.

与以上相同,但Offset 为0.

Note that offsets are counted in bytes, not in characters. If the file is opened using some other encoding than latin1, one byte does not correspond to one character. Positioning in such a file can only be done to known character boundaries, i.e. to a position earlier retrieved by getting a current position, to the beginning/end of the file or to some other position known to be on a correct character boundary by some other means (typically beyond a byte order mark in the file, which has a known byte-size).

注意, 偏移量的单位是字节而不是字符. 如果文件以其他的encoding 而不是latin1打开时, 一个字节并不对应一个字符. Positioning in such a file can only be done to known character boundaries, i.e. to a position earlier retrieved by getting a current position, to the beginning/end of the file or to some other position known to be on a correct character boundary by some other means (typically beyond a byte order mark in the file, which has a known byte-size).

Typical error reasons are:

典型的错误原因:

einval

Either Location was illegal, or it evaluated to a negative offset in the file. Note that if the resulting position is a negative value, the result is an error, and after the call the file position is undefined.

Location 不合法或者计算出一个文件的负偏移量 negative offset in the file. Note that if the resulting position is a negative value, the result is an error, and after the call the file position is undefined.

pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason}

IoDevice = io_device(),
LocNums = [{Location = location(), Number = non_neg_integer()}],
DataL = [Data],
Data = string() | binary() | eof,
Reason = posix() | badarg | terminated

Performs a sequence of pread/3 in one operation, which is more efficient than calling them one at a time. Returns {ok, [Data, ...]} or {error, Reason}, where each Data, the result of the corresponding pread, is either a list or a binary depending on the mode of the file, or eof if the requested position was beyond end of file.

As the position is given as a byte-offset, special caution has to be taken when working with files where encoding is set to something else than latin1, as not every byte position will be a valid character boundary on such a file.

pread(IoDevice, Location, Number) -> {ok, Data} | eof | {error, Reason}

IoDevice = io_device(),
Location = location(),
Number = non_neg_integer(),
Data = string() | binary(),
Reason = posix() | badarg | terminated

Combines position/2 and read/2 in one operation, which is more efficient than calling them one at a time. If IoDevice has been opened in raw mode, some restrictions apply: Location is only allowed to be an integer; and the current position of the file is undefined after the operation.

As the position is given as a byte-offset, special caution has to be taken when working with files where encoding is set to something else than latin1, as not every byte position will be a valid character boundary on such a file.

pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}}

IoDevice = io_device(),
LocBytes = [{Location = location(), Bytes = iodata()}],
N = non_neg_integer(),
Reason = posix() | badarg | terminated

Performs a sequence of pwrite/3 in one operation, which is more efficient than calling them one at a time. Returns ok or {error, {N, Reason}}, where N is the number of successful writes that was done before the failure.

When positioning in a file with other encoding than latin1, caution must be taken to set the position on a correct character boundary, see position/2 for details.

pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason}

IoDevice = io_device(),
Location = location(),
Bytes = iodata(),
Reason = posix() | badarg | terminated

Combines position/2 and write/2 in one operation, which is more efficient than calling them one at a time. If IoDevice has been opened in raw mode, some restrictions apply: Location is only allowed to be an integer; and the current position of the file is undefined after the operation.

When positioning in a file with other encoding than latin1, caution must be taken to set the position on a correct character boundary, see position/2 for details.

read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason}

IoDevice = io_device() | atom(),
Number = non_neg_integer(),
Data = string() | binary(),
Reason = posix() | badarg | terminated

Reads Number bytes/characters from the file referenced by IoDevice. The functions read/2, pread/3 and read_line/1 are the only ways to read from a file opened in raw mode (although they work for normally opened files, too).

For files where encoding is set to something else than latin1, one character might be represented by more than one byte on the file. The parameter Number always denotes the number of characters read from the file, why the position in the file might be moved a lot more than this number when reading a Unicode file.

Also if encoding is set to something else than latin1, the read/3 call will fail if the data contains characters larger than 255, why the io(3) module 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 are returned in a binary, otherwise in a list. The list or binary will be shorter than the number of bytes requested if end of file was reached.

eof

Returned if Number>0 and 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 was opened with another encoding than latin1 and the data in the file can not be translated to the byte-oriented data that this function returns.

read_file(Filename) -> {ok, Binary} | {error, Reason}

Filename = name(),
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.

Typical error reasons:

典型的错误原因:

enoent

The file does not exist.

eacces

Missing permission for reading the file, or for searching one of the parent directories.

eisdir

The named file is a directory.

enotdir

A component of the file name is not a directory. On some platforms, enoent is returned instead.

enomem

There is not enough memory for the contents of the file.

read_file_info(Filename) -> {ok, FileInfo} | {error, Reason}

Filename = name(),
FileInfo = file_info(),
Reason = posix() | badarg

read_file_info(Filename, Opts) -> {ok, FileInfo} | {error, Reason}

Filename = name(),
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 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}. Type local will return local time, universal will return universal time and posix will return seconds since or before unix time epoch which is 1970-01-01 00:00 UTC. Default is {time, local}.

Note:

Since file times is stored in posix time on most OS it is faster to query file information with the posix option.

The record file_info contains the following fields.

size = integer()

Size of file in bytes.

type = device | directory | regular | other

The type of the file.

access = read | write | read_write | none

The current system access to the file.

atime = date_time() | integer()

The last time the file was read.

mtime = date_time() | integer()

The last time the file was written.

ctime = date_time() | integer()

The interpretation of this time field depends on the operating system. On Unix, it is the last time the file or the inode was changed. In Windows, it is the create time.

mode = integer()

The file permissions as the sum of the following bit values:

8#00400

read permission: owner

8#00200

write permission: owner

8#00100

execute permission: owner

8#00040

read permission: group

8#00020

write permission: group

8#00010

execute permission: group

8#00004

read permission: other

8#00002

write permission: other

8#00001

execute permission: other

16#800

set user id on execution

16#400

set group id on execution

On Unix platforms, other bits than those listed above may be set.

links = integer()

Number of links to the file (this will always be 1 for file systems which have no concept of links).

major_device = integer()

Identifies the file system where the file is located. In Windows, the number indicates a drive as follows: 0 means A:, 1 means B:, and so on.

minor_device = integer()

Only valid for character devices on Unix. In all other cases, this field is zero.

inode = integer()

Gives the inode number. On non-Unix file systems, this field will be zero.

uid = integer()

Indicates the owner of the file. Will be zero for non-Unix file systems.

gid = integer()

Gives the group that the owner of the file belongs to. Will be zero 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 file name is not a directory. On some platforms, enoent is returned instead.

read_line(IoDevice) -> {ok, Data} | eof | {error, Reason}

IoDevice = io_device() | atom(),
Data = string() | binary(),
Reason = posix() | badarg | terminated

Reads a line of bytes/characters from the file referenced by IoDevice. 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 a 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.

The function can be used on files opened in raw mode. It is however inefficient to use it on raw files if the file is not opened with the option {read_ahead, Size} specified, why combining raw and {read_ahead, Size} is highly recommended when opening a text file for raw line oriented reading.

If encoding is set to something else than latin1, the read_line/1 call will fail if the data contains characters larger than 255, why the io(3) module 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 was 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 was opened with another encoding than latin1 and the data on the file can not be translated to the byte-oriented data that this function returns.

read_link(Name) -> {ok, Filename} | {error, Reason}

Name = name(),
Filename = filename(),
Reason = posix() | badarg

This function 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 will be {error,enotsup}.

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.

Name = name(),
FileInfo = file_info(),
Reason = posix() | badarg
Name = name(),
Opts = [file_info_option()],
FileInfo = file_info(),
Reason = posix() | badarg

This function works like read_file_info/1,2 except that if Name is a symbolic link, information about the link will be returned in the file_info record and the type field of the record will be set to symlink.

If Name is not a symbolic link, this function returns exactly the same result as read_file_info/1. On platforms that do not support symbolic links, this function is always equivalent to read_file_info/1.

rename(Source, Destination) -> ok | {error, Reason}

Source = name(),
Destination = name(),
Reason = posix() | badarg

Tries to rename the file Source to Destination. It can be used to move files (and directories) between directories, but it is not sufficient to specify the destination only. The destination file name must also be specified. For example, if bar is a normal file and foo and baz are directories, rename("foo/bar", "baz") returns an error, but rename("foo/bar", "baz/bar") succeeds. Returns ok if it is successful.

Note:

Renaming of open files is not allowed on most platforms (see eacces below).

Typical error reasons:

典型的错误原因:

eacces

Missing read or write permissions for the parent directories of Source or Destination. On some platforms, this error is given if either Source or Destination is open.

eexist

Destination is not an empty directory. On some platforms, also given when Source and Destination are not of the same type.

einval

Source is a root directory, or Destination is a sub-directory of Source.

eisdir

Destination is a directory, but Source is not.

enoent

Source does not exist.

enotdir

Source is a directory, but Destination is not.

exdev

Source and Destination are on different file systems.

script(Filename) -> {ok, Value} | {error, Reason}

Filename = name(),
Value = term(),
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 the file. Returns one of the following:

{ok, Value}

The file was read and evaluated. Value is the value of the last expression.

{error, atom()}

An error occurred when opening the file or reading it. See open/2 for a list of typical error codes.

{error, {Line, Mod, Term}}

An error occurred when interpreting the Erlang expressions in the file. Use format_error/1 to convert the three-element tuple to an English description of the error.

当翻译文件中的Erlang项时发生一个错误. 使用format_error/1来将三元素的元组翻译成错误的英文描述.

script(Filename, Bindings) -> {ok, Value} | {error, Reason}

Filename = name(),
Bindings = erl_eval:binding_struct(),
Value = term(),
Reason = posix() | badarg | terminated | system_limit
| {Line = integer(), Mod = module(), Term = term()}

The same as script/1 but the variable bindings Bindings are used in the evaluation. See erl_eval(3) about variable bindings.

set_cwd(Dir) -> ok | {error, Reason}

Dir = name(),
Reason = posix() | badarg

Sets the current working directory of the file server to Dir. Returns ok if successful.

Typical error reasons are:

典型的错误原因:

enoent

The directory does not exist.

enotdir

A component of Dir is not a directory. On some platforms, enoent is returned.

eacces

Missing permission for the directory or one of its parents.

badarg

Dir had an improper type, such as tuple.

Warning:

In a future release, a bad type for the Dir argument will probably generate an exception.

sync(IoDevice) -> ok | {error, Reason}

IoDevice = io_device(),
Reason = posix() | badarg | terminated

Makes sure that any buffers kept by the operating system (not by the Erlang runtime system) are written to disk. On some platforms, this function might have no effect.

Typical error reasons are:

典型的错误原因:

enospc

Not enough space left to write the file.

datasync(IoDevice) -> ok | {error, Reason}

IoDevice = io_device(),
Reason = posix() | badarg | terminated

Makes sure that any buffers kept by the operating system (not by the Erlang runtime system) are written to disk. In many ways it's resembles fsync but it not requires to update some of file's metadata such as the access time. On some platforms, this function might have no effect.

Applications that access databases or log files often write a tiny data fragment (e.g., one line in a log file) and then call fsync() immediately in order to ensure that the written data is physically stored on the harddisk. Unfortunately, fsync() will always initiate two write operations: one for the newly written data and another one in order 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 implementing the fdatasync syscall.

truncate(IoDevice) -> ok | {error, Reason}

IoDevice = io_device(),
Reason = posix() | badarg | terminated

Truncates the file referenced by IoDevice at the current position. Returns ok if successful, otherwise {error, Reason}.

sendfile(Filename, Socket) -> {'ok', non_neg_integer()} | {'error', inet:posix() | closed | badarg | not_owner} types: Filename = file:name(), Socket = inet:socket()

Sends the file Filename to Socket. Returns {ok, BytesSent} if successful, otherwise {error, Reason}.

sendfile(RawFile, Socket, Offset, Bytes, Opts) -> {'ok', non_neg_integer()} | {'error', inet:posix() | closed | badarg | not_owner}

RawFile = file:fd(),
Socket = inet:socket(),
Offset = non_neg_integer(),
Bytes = non_neg_integer(),
Opts = [sendfile_option()]

Sends Bytes from the file referenced by RawFile beginning at Offset to Socket. Returns {ok, BytesSent} if successful, otherwise {error, Reason}. If Bytes is set to 0 all data after the given Offset is 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

If the OS used does not support sendfile, an Erlang fallback using file:read and gen_tcp:send is used.

The option list can contain the following options:

chunk_size

The chunk size used by the erlang fallback to send data. If using the fallback, this should be set to a value which comfortably fits in the systems memory. Default is 20 MB.

On operating systems with thread support, it is recommended to use async threads. See the command line flag +A in erl(1). If it is not possible to use async threads for sendfile, it is recommended to use a relatively small value for the send buffer on the socket. Otherwise the Erlang VM might loose some of its soft realtime guarantees. Which size to use depends on the OS/hardware and the requirements of the application.

write(IoDevice, Bytes) -> ok | {error, Reason}

IoDevice = io_device() | atom(),
Bytes = iodata(),
Reason = posix() | badarg | terminated

Writes Bytes to the file referenced by IoDevice. This function is the only way to write to a file opened in raw mode (although it works for normally opened files, too). Returns ok if successful, and {error, Reason} otherwise.

If the file is opened with encoding set to something else than latin1, each byte written might result in several bytes actually being written to the file, as the byte range 0..255 might represent anything between one and four bytes depending on value and UTF encoding type.

Typical error reasons are:

典型的错误原因:

ebadf

The file is not opened for writing.

enospc

There is a no space left on the device.

write_file(Filename, Bytes) -> ok | {error, Reason}

Filename = name(),
Bytes = iodata(),
Reason = posix() | badarg | terminated | system_limit

Writes the contents of the iodata term Bytes to the file Filename. The file is created if it does not exist. If it exists, the previous contents are overwritten. Returns ok, or {error, Reason}.

Typical error reasons are:

典型的错误原因:

enoent

A component of the file name does not exist.

enotdir

A component of the file name is not a directory. On some platforms, enoent is returned instead.

enospc

There is a no space left on the device.

eacces

Missing permission for writing the file or searching one of the parent directories.

eisdir

The named file is a directory.

write_file(Filename, Bytes, Modes) -> ok | {error, Reason}

Filename = name(),
Bytes = iodata(),
Modes = [mode()],
Reason = posix() | badarg | terminated | system_limit

Same as write_file/2, but takes a third argument Modes, a list of possible modes, see open/2. The mode flags binary and write are implicit, so they should not be used.

write_file_info(Filename, FileInfo) -> ok | {error, Reason}

Filename = name(),
FileInfo = file_info(),
Reason = posix() | badarg

write_file_info(Filename, FileInfo, Opts) -> ok | {error, Reason}

Filename = name(),
Opts = [file_info_option()],
FileInfo = file_info(),
Reason = posix() | badarg

Change file information. Returns ok if successful, otherwise {error, Reason}. FileInfo is a record file_info, defined in the Kernel include file file.hrl. Include the following directive in the module from which the function is called:

-include_lib("kernel/include/file.hrl").

The time type set in atime, mtime and ctime is dependent on the time type set in Opts :: {time, Type}. Type local will interpret the time set as local, universal will interpret it as universal time and posix must be seconds since or before unix time epoch which is 1970-01-01 00:00 UTC. Default is {time, local}.

The following fields are used from the record, if they are given.

atime = date_time() | integer()

The last time the file was read.

mtime = date_time() | integer()

The last time the file was written.

ctime = date_time() | integer()

On Unix, any value give for this field will be ignored (the "ctime" for the file will be set to the current time). On Windows, this field is the new creation time to set for the file.

mode = integer()

The file permissions as the sum of the following bit values:

8#00400

read permission: owner

8#00200

write permission: owner

8#00100

execute permission: owner

8#00040

read permission: group

8#00020

write permission: group

8#00010

execute permission: group

8#00004

read permission: other

8#00002

write permission: other

8#00001

execute permission: other

16#800

set user id on execution

16#400

set group id on execution

On Unix platforms, other bits than those listed above may be set.

uid = integer()

Indicates the owner of the file. Ignored for non-Unix file systems.

gid = integer()

Gives the group that the owner of the file belongs to. Ignored 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 file name is not a directory. On some platforms, enoent is returned instead.

POSIX Error Codes

eacces - permission denied

eagain - resource temporarily unavailable

ebadf - bad file number

ebusy - file busy

edquot - disk quota exceeded

eexist - file already exists

efault - bad address in system call argument

efbig - file too large

eintr - interrupted system call

einval - invalid argument

eio - IO error

eisdir - illegal operation on a directory

eloop - too many levels of symbolic links

emfile - too many open files

emlink - too many links

enametoolong - file name too long

enfile - file table overflow

enodev - no such device

enoent - no such file or directory

enomem - not enough memory

enospc - no space left on device

enotblk - block device required

enotdir - not a directory

enotsup - operation not supported

enxio - no such device or address

eperm - not owner

epipe - broken pipe

erofs - read-only file system

espipe - invalid seek

esrch - no such process

estale - stale remote file handle

exdev - cross-domain link

Performance

Some operating system file operations, for example a sync/1 or close/1 on a huge file, may block their calling thread for seconds. If this befalls the emulator main thread, the response time is no longer in the order of milliseconds, depending on the definition of "soft" in soft real-time system.

If the device driver thread pool is active, file operations are done through those threads instead, so the emulator can go on executing Erlang processes. Unfortunately, the time for serving a file operation increases due to the extra scheduling required from the operating system.

If the device driver thread pool is disabled or of size 0, large file reads and writes are segmented into several smaller, which enables the emulator so server other processes during the file operation. This gives the same effect as when using the thread pool, but with larger overhead. Other file operations, for example sync/1 or close/1 on a huge file, still are a problem.

For increased performance, raw files are recommended. Raw files uses the file system of the node's host machine. 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 another node's, and the other node runs on some other host machine, they may have different file systems. This is seldom a problem, but you have now been warned.

A normal file is really a process so it can be used as an IO 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 another node's, also binaries are copied.

Caching data to reduce the number of file operations, or rather the number of calls to the file driver, will generally increase performance. The following function writes 4 MBytes in 23 seconds when tested:

= 0 ->
    {ok, FD} = file:open(Name, [raw, write, delayed_write, binary]),
    ok = create_file_slow(FD, 0, N),
    ok = ?FILE_MODULE:close(FD),
    ok.
      
create_file_slow(FD, M, M) ->
    ok;
create_file_slow(FD, M, N) ->
    ok = file:write(FD, <>),
    create_file_slow(FD, M+1, N).]]>

The following, functionally equivalent, function collects 1024 entries into a list of 128 32-byte binaries before each call to file:write/2 and so does the same work in 0.52 seconds, which is 44 times faster.

= 0 ->
    {ok, FD} = file:open(Name, [raw, write, delayed_write, binary]),
    ok = create_file(FD, 0, N),
    ok = ?FILE_MODULE:close(FD),
    ok.
      
create_file(FD, M, M) ->
    ok;
create_file(FD, M, N) when M + 1024 =< N ->
    create_file(FD, M, M + 1024, []),
    create_file(FD, M + 1024, N);
create_file(FD, M, N) ->
    create_file(FD, M, N, []).
      
create_file(FD, M, M, R) ->
    ok = file:write(FD, R);
create_file(FD, M, N0, R) when M + 8 =< N0 ->
    N1  = N0-1,  N2  = N0-2,  N3  = N0-3,  N4  = N0-4, 
    N5  = N0-5,  N6  = N0-6,  N7  = N0-7,  N8  = N0-8, 
    create_file(FD, M, N8, 
                [<> | R]);
create_file(FD, M, N0, R) ->
    N1 = N0-1,
    create_file(FD, M, N1, [<> | R]).]]>

Note:

Trust only your own benchmarks. If the list length in create_file/2 above is increased, it will run slightly faster, but consume more memory and cause more memory fragmentation. How much this affects your application is something that this simple benchmark can not predict.

If the size of each binary is increased to 64 bytes, it will also run slightly faster, but the code will be twice as clumsy. In the current implementation are binaries larger than 64 bytes stored in memory common to all processes and not copied when sent between processes, while these smaller binaries are stored on the process heap and copied when sent like any other term.

So, with a binary size of 68 bytes create_file/2 runs 30 percent slower then with 64 bytes, and will cause much more memory fragmentation. Note that if the binaries were to be sent between processes (for example a non-raw file) the results would probably be completely different.

A raw file is really a port. When writing data to a port, it is efficient to write a list of binaries. There is no need 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 file:write(FD, [Bin1, Bin2 | Bin3]) will write the contents of the binaries without copying the data at all except for perhaps deep down in the operating system kernel.

For raw files, pwrite/2 and pread/2 are efficiently implemented. The file driver is called only once for the whole operation, and the list iteration is done in the file driver.

The options delayed_write and read_ahead to file:open/2 makes the file driver cache data to reduce the number of operating system calls. The function create_file/2 in the example above takes 60 seconds seconds without the delayed_write option, which is 2.6 times slower.

And, as a really bad example, create_file_slow/2 above without the raw, binary and delayed_write options, that is it calls file:open(Name, [write]), needs 1 min 20 seconds for the job, which is 3.5 times slower than the first example, and 150 times slower than the optimized create_file/2.

Warnings

If an error occurs when accessing an open file with the io module, the process which handles the file will exit. The dead file process might hang if a process tries to access it later. This will be fixed in a future release.

If an error occurs when accessing an open file with the io module, the process which handles the file will exit. The dead file process might hang if a process tries to access it later. This will be fixed in a future release.

SEE ALSO

filename(3)