PageRenderTime 20ms CodeModel.GetById 3ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 1ms

/erlang_otp/_sources/lib/kernel-2.13.3/doc/html/file.txt

https://bitbucket.org/docs/docs.bitbucket.org
Plain Text | 1623 lines | 1114 code | 509 blank | 0 comment | 0 complexity | 85b7ef4fe58eb6859ca23f50325d08d9 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1=======================================
   2Lib - Kernel-2.13.3 - Doc - Html - File
   3=======================================
   4
   5` <http://www.ericsson.com/technology/opensource/erlang>`__
   6
   7
   8file
   9====
  10
  11
  12
  13MODULE
  14~~~~~~
  15file
  16
  17
  18MODULE SUMMARY
  19~~~~~~~~~~~~~~
  20File Interface Module
  21
  22
  23DESCRIPTION
  24~~~~~~~~~~~
  25
  26The module file provides an interface to the file system.
  27
  28On operating systems with thread support, it is possible to let file
  29operations be performed in threads of their own, allowing other Erlang
  30processes to continue executing in parallel with the file operations.
  31See the command line flag+A in `erl(1)
  32<javascript:erlhref('../../../../',%20'erts',%20'erl.html');>`__.
  33
  34
  35
  36DATA TYPES
  37~~~~~~~~~~
  38
  39
  40.. sourcecode:: erlang
  41
  42    
  43    iodata() = iolist() | binary()
  44      iolist() = [char() | binary() | iolist()]
  45    
  46    io_device()
  47      as returned by file:open/2, a process handling IO protocols
  48    
  49    name() = string() | atom() | DeepList
  50      DeepList = [char() | atom() | DeepList]
  51    
  52    posix()
  53      an atom which is named from the Posix error codes used in
  54      Unix, and in the runtime libraries of most C compilers
  55    
  56    ext_posix() = posix() | badarg
  57    
  58    time() = {{Year, Month, Day}, {Hour, Minute, Second}}
  59      Year = Month = Day = Hour = Minute = Second = int()
  60      Must denote a valid date and time
  61
  62
  63
  64
  65EXPORTS
  66~~~~~~~
  67
  68change_group(Filename, Gid) -> ok | {error, Reason}
  69
  70
  71Types:
  72
  73Filename = name()
  74Gid = int()
  75Reason = ext_posix()
  76
  77
  78Changes group of a file. Seewrite_file_info/2.
  79
  80change_owner(Filename, Uid) -> ok | {error, Reason}
  81
  82
  83Types:
  84
  85Filename = name()
  86Uid = int()
  87Reason = ext_posix()
  88
  89
  90Changes owner of a file. Seewrite_file_info/2.
  91
  92change_owner(Filename, Uid, Gid) -> ok | {error, Reason}
  93
  94
  95Types:
  96
  97Filename = name()
  98Uid = int()
  99Gid = int()
 100Reason = ext_posix()
 101
 102
 103Changes owner and group of a file. Seewrite_file_info/2.
 104
 105change_time(Filename, Mtime) -> ok | {error, Reason}
 106
 107
 108Types:
 109
 110Filename = name()
 111Mtime = time()
 112Reason = ext_posix()
 113
 114
 115Changes the modification and access times of a file.
 116Seewrite_file_info/2.
 117
 118change_time(Filename, Mtime, Atime) -> ok | {error, Reason}
 119
 120
 121Types:
 122
 123Filename = name()
 124Mtime = Atime = time()
 125Reason = ext_posix()
 126
 127
 128Changes the modification and last access times of a file.
 129Seewrite_file_info/2.
 130
 131close(IoDevice) -> ok | {error, Reason}
 132
 133
 134Types:
 135
 136IoDevice = io_device()
 137Reason = ext_posix() | terminated
 138
 139
 140Closes the file referenced by IoDevice. It mostly returns ok, expect
 141for some severe errors such as out of memory.
 142
 143Note that if the option delayed_write was used when opening the file,
 144close/1 might return an old write error and not even try to close the
 145file. Seeopen/2.
 146
 147consult(Filename) -> {ok, Terms} | {error, Reason}
 148
 149
 150Types:
 151
 152Filename = name()
 153Terms = [term()]
 154Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 155�Line, Mod, Term -- see below
 156
 157
 158Reads Erlang terms, separated by '.', from Filename. Returns one of
 159the following:
 160
 161:{ok, Terms}: The file was successfully read.
 162:{error, atom()}: An error occurred when opening the file or reading
 163  it. See open/2 for a list of typical error codes.
 164:{error, {Line, Mod, Term}}: An error occurred when interpreting the
 165  Erlang terms in the file. Use format_error/1 to convert the three-
 166  element tuple to an English description of the error.
 167
 168
 169Example:
 170
 171
 172.. sourcecode:: erlang
 173
 174    
 175    f.txt:  {person, "kalle", 25}.
 176            {person, "pelle", 30}.
 177
 178
 179
 180.. sourcecode:: erlang
 181
 182    
 183    1> file:consult("f.txt").
 184    {ok,[{person,"kalle",25},{person,"pelle",30}]}
 185
 186
 187copy(Source, Destination) ->
 188copy(Source, Destination, ByteCount) -> {ok, BytesCopied} | {error,
 189Reason}
 190
 191
 192Types:
 193
 194Source = Destination = io_device() | Filename | {Filename, Modes}
 195�Filename = name()
 196�Modes = [Mode] -- see open/2
 197ByteCount = int() >= 0 | infinity
 198BytesCopied = int()
 199
 200
 201Copies ByteCount bytes from Source toDestination. Source and
 202Destination refer to either filenames or IO devices from e.g.
 203open/2.ByteCount defaults infinity, denoting an infinite number of
 204bytes.
 205
 206The argument Modes is a list of possible modes, seeopen/2, and
 207defaults to [].
 208
 209If both Source and Destination refer to filenames, the files are
 210opened with [read, binary] and [write, binary] prepended to their mode
 211lists, respectively, to optimize the copy.
 212
 213If Source refers to a filename, it is opened withread mode prepended
 214to the mode list before the copy, and closed when done.
 215
 216If Destination refers to a filename, it is opened with write mode
 217prepended to the mode list before the copy, and closed when done.
 218
 219Returns {ok, BytesCopied} where BytesCopied is the number of bytes
 220that actually was copied, which may be less than ByteCount if end of
 221file was encountered on the source. If the operation fails, {error,
 222Reason} is returned.
 223
 224Typical error reasons: As for open/2 if a file had to be opened, and
 225as for read/2 and write/2.
 226
 227del_dir(Dir) -> ok | {error, Reason}
 228
 229
 230Types:
 231
 232Dir = name()
 233Reason = ext_posix()
 234
 235
 236Tries to delete the directory Dir. The directory must be empty before
 237it can be deleted. Returns ok if successful.
 238
 239Typical error reasons are:
 240
 241:eacces: Missing search or write permissions for the parent
 242  directories of Dir.
 243:eexist: The directory is not empty.
 244:enoent: The directory does not exist.
 245:enotdir: A component of Dir is not a directory. On some platforms,
 246  enoent is returned instead.
 247:einval: Attempt to delete the current directory. On some platforms,
 248  eacces is returned instead.
 249
 250
 251delete(Filename) -> ok | {error, Reason}
 252
 253
 254Types:
 255
 256Filename = name()
 257Reason = ext_posix()
 258
 259
 260Tries to delete the file Filename. Returns ok if successful.
 261
 262Typical error reasons are:
 263
 264:enoent: The file does not exist.
 265:eacces: Missing permission for the file or one of its parents.
 266:eperm: The file is a directory and the user is not super-user.
 267:enotdir: A component of the file name is not a directory. On some
 268  platforms, enoent is returned instead.
 269:einval: Filename had an improper type, such as tuple.
 270
 271Warning
 272In a future release, a bad type for the Filename argument will
 273probably generate an exception.
 274
 275
 276
 277eval(Filename) -> ok | {error, Reason}
 278
 279
 280Types:
 281
 282Filename = name()
 283Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 284�Line, Mod, Term -- see below
 285
 286
 287Reads and evaluates Erlang expressions, separated by '.' (or ',', a
 288sequence of expressions is also an expression), fromFilename. The
 289actual result of the evaluation is not returned; any expression
 290sequence in the file must be there for its side effect. Returns one of
 291the following:
 292
 293:ok: The file was read and evaluated.
 294:{error, atom()}: An error occurred when opening the file or reading
 295  it. See open/2 for a list of typical error codes.
 296:{error, {Line, Mod, Term}}: An error occurred when interpreting the
 297  Erlang expressions in the file. Use format_error/1 to convert the
 298  three-element tuple to an English description of the error.
 299
 300
 301eval(Filename, Bindings) -> ok | {error, Reason}
 302
 303
 304Types:
 305
 306Filename = name()
 307Bindings -- see erl_eval(3)
 308Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 309�Line, Mod, Term -- see eval/1
 310
 311
 312The same as eval/1 but the variable bindingsBindings are used in the
 313evaluation. See `erl_eval(3) <javascript:erlhref('../../../../',%20'st
 314dlib',%20'erl_eval.html');>`__ about variable bindings.
 315
 316file_info(Filename) -> {ok, FileInfo} | {error, Reason}
 317
 318
 319This function is obsolete. Use read_file_info/1 instead.
 320
 321format_error(Reason) -> Chars
 322
 323
 324Types:
 325
 326Reason = atom() | {Line, Mod, Term}
 327�Line, Mod, Term -- see eval/1
 328Chars = [char() | Chars]
 329
 330
 331Given the error reason returned by any function in this module,
 332returns a descriptive string of the error in English.
 333
 334get_cwd() -> {ok, Dir} | {error, Reason}
 335
 336
 337Types:
 338
 339Dir = string()
 340Reason = posix()
 341
 342
 343Returns {ok, Dir}, where Dir is the current working directory of the
 344file server.
 345Note
 346In rare circumstances, this function can fail on Unix. It may happen
 347if read permission does not exist for the parent directories of the
 348current directory.
 349
 350Typical error reasons are:
 351
 352:eacces: Missing read permission for one of the parents of the current
 353  directory.
 354
 355
 356get_cwd(Drive) -> {ok, Dir} | {error, Reason}
 357
 358
 359Types:
 360
 361Drive = string() -- see below
 362Dir = string()
 363Reason = ext_posix()
 364
 365
 366Drive should be of the form "Letter:", for example "c:". Returns {ok,
 367Dir} or{error, Reason}, where Dir is the current working directory of
 368the drive specified.
 369
 370This function returns {error, enotsup} on platforms which have no
 371concept of current drive (Unix, for example).
 372
 373Typical error reasons are:
 374
 375:enotsup: The operating system have no concept of drives.
 376:eacces: The drive does not exist.
 377:einval: The format of Drive is invalid.
 378
 379
 380list_dir(Dir) -> {ok, Filenames} | {error, Reason}
 381
 382
 383Types:
 384
 385Dir = name()
 386Filenames = [Filename]
 387�Filename = string()
 388Reason = ext_posix()
 389
 390
 391Lists all the files in a directory. Returns{ok, Filenames} if
 392successful. Otherwise, it returns{error, Reason}. Filenames is a list
 393of the names of all the files in the directory. The names are not
 394sorted.
 395
 396Typical error reasons are:
 397
 398:eacces: Missing search or write permissions for Dir or one of its
 399  parent directories.
 400:enoent: The directory does not exist.
 401
 402
 403make_dir(Dir) -> ok | {error, Reason}
 404
 405
 406Types:
 407
 408Dir = name()
 409Reason = ext_posix()
 410
 411
 412Tries to create the directory Dir. Missing parent directories are not
 413created. Returns ok if successful.
 414
 415Typical error reasons are:
 416
 417:eacces: Missing search or write permissions for the parent
 418  directories of Dir.
 419:eexist: There is already a file or directory named Dir.
 420:enoent: A component of Dir does not exist.
 421:enospc: There is a no space left on the device.
 422:enotdir: A component of Dir is not a directory. On some platforms,
 423  enoent is returned instead.
 424
 425
 426make_link(Existing, New) -> ok | {error, Reason}
 427
 428
 429Types:
 430
 431Existing = New = name()
 432Reason = ext_posix()
 433
 434
 435Makes a hard link from Existing to New, on platforms that support
 436links (Unix). This function returnsok if the link was successfully
 437created, or{error, Reason}. On platforms that do not support links,
 438{error,enotsup} is returned.
 439
 440Typical error reasons:
 441
 442:eacces: Missing read or write permissions for the parent directories
 443  of Existing or New.
 444:eexist: New already exists.
 445:enotsup: Hard links are not supported on this platform.
 446
 447
 448make_symlink(Name1, Name2) -> ok | {error, Reason}
 449
 450
 451Types:
 452
 453Name1 = Name2 = name()
 454Reason = ext_posix()
 455
 456
 457This function creates a symbolic link Name2 to the file or directory
 458Name1, on platforms that support symbolic links (most Unix systems).
 459Name1 need not exist. This function returns ok if the link was
 460successfully created, or {error, Reason}. On platforms that do not
 461support symbolic links, {error, enotsup} is returned.
 462
 463Typical error reasons:
 464
 465:eacces: Missing read or write permissions for the parent directories
 466  of Name1 or Name2.
 467:eexist: Name2 already exists.
 468:enotsup: Symbolic links are not supported on this platform.
 469
 470
 471open(Filename, Modes) -> {ok, IoDevice} | {error, Reason}
 472
 473
 474Types:
 475
 476Filename = name()
 477Modes = [Mode]
 478�Mode = read | write | append | raw | binary | {delayed_write, Size,
 479Delay} | delayed_write | {read_ahead, Size} | read_ahead | compressed
 480��Size = Delay = int()
 481IoDevice = io_device()
 482Reason = ext_posix() | system_limit
 483
 484
 485Opens the file Filename in the mode determined byModes, which may
 486contain one or more of the following items:
 487
 488:read: The file, which must exist, is opened for reading.
 489:write: The file is opened for writing. It is created if it does not
 490  exist. If the file exists, and if write is not combined with read, the
 491  file will be truncated.
 492:append: The file will be opened for writing, and it will be created
 493  if it does not exist. Every write operation to a file opened with
 494  append will take place at the end of the file.
 495:raw: The raw option allows faster access to a file, because no Erlang
 496process is needed to handle the file. However, a file opened in this
 497way has the following limitations:
 498
 499    + The functions in the io module cannot be used, because they can only
 500      talk to an Erlang process. Instead, use the read/2, read_line/1 and
 501      write/2 functions.
 502    + Especially if read_line/1 is to be used on a raw file, it is
 503      recommended to combine this option with the {read_ahead, Size} option
 504      as line oriented I/O is inefficient without buffering.
 505    + Only the Erlang process which opened the file can use it.
 506    + A remote Erlang file server cannot be used; the computer on which
 507      the Erlang node is running must have access to the file system
 508      (directly or through NFS).
 509
 510:binary: When this option has been given, read operations on the file
 511  will return binaries rather than lists.
 512:{delayed_write, Size, Delay}: If this option is used, the data in
 513  subsequentwrite/2 calls is buffered until there are at leastSize bytes
 514  buffered, or until the oldest buffered data is Delay milliseconds old.
 515  Then all buffered data is written in one operating system call. The
 516  buffered data is also flushed before some other file operation than
 517  write/2 is executed. The purpose of this option is to increase
 518  performance by reducing the number of operating system calls, so
 519  thewrite/2 calls should be for sizes significantly less than Size, and
 520  not interspersed by to many other file operations, for this to happen.
 521  When this option is used, the result of write/2 calls may prematurely
 522  be reported as successful, and if a write error should actually occur
 523  the error is reported as the result of the next file operation, which
 524  is not executed. For example, when delayed_write is used, after a
 525  number of write/2 calls, close/1 might return {error, enospc} because
 526  there was not enough space on the disc for previously written data,
 527  andclose/1 should probably be called again since the file is still
 528  open.
 529:delayed_write: The same as {delayed_write, Size, Delay} with
 530  reasonable default values for Size andDelay. (Roughly some 64 KBytes,
 531  2 seconds)
 532:{read_ahead, Size}: This option activates read data buffering.
 533  Ifread/2 calls are for significantly less thanSize bytes, read
 534  operations towards the operating system are still performed for blocks
 535  of Size bytes. The extra data is buffered and returned in subsequent
 536  read/2 calls, giving a performance gain since the number of operating
 537  system calls is reduced. The read_ahead buffer is also highly utilized
 538  by the read_line/1 function in raw mode, why this option is
 539  recommended (for performance reasons) when accessing raw files using
 540  that function. If read/2 calls are for sizes not significantly less
 541  than, or even greater than Size bytes, no performance gain can be
 542  expected.
 543:read_ahead: The same as {read_ahead, Size} with a reasonable default
 544  value for Size. (Roughly some 64 KBytes)
 545:compressed: Makes it possible to read or write gzip compressed files.
 546  The compressesed option must be combined with either read or write,
 547  but not both. Note that the file size obtained withread_file_info/1
 548  will most probably not match the number of bytes that can be read from
 549  a compressed file.
 550:{encoding, Encoding}: Makes the file perform automatic translation of
 551characters to and from a specific (Unicode) encoding. Note that the
 552data supplied to file:write or returned by file:read still is byte
 553oriented, this option only denotes how data is actually stored in the
 554disk file. Depending on the encoding, different methods of reading and
 555writing data is preferred. The default encoding of latin1 implies
 556using this (the file) module for reading and writing data, as the
 557interfaces provided here work with byte-oriented data, while using
 558other (Unicode) encodings makes the `io(3)
 559<javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__
 560module's get_chars, get_line and put_chars functions more suitable, as
 561they can work with the full Unicode range. If data is sent to an
 562io_device() in a format that cannot be converted to the specified
 563encoding, or if data is read by a function that returns data in a
 564format that cannot cope with the character range of the data, an error
 565occurs and the file will be closed. The allowed values for Encoding
 566are:
 567    :latin1: The default encoding. Bytes supplied to i.e. file:write are
 568      written as is on the file, likewise bytes read from the file are
 569      returned to i.e. file:read as is. If the `io(3)
 570      <javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__
 571      module is used for writing, the file can only cope with Unicode
 572      characters up to codepoint 255 (the ISO-latin-1 range).
 573    :unicode or utf8: Characters are translated to and from the UTF-8
 574      encoding before being written to or read from the file. A file opened
 575      in this way might be readable using the file:read function, as long as
 576      no data stored on the file lies beyond the ISO-latin-1 range (0..255),
 577      but failure will occur if the data contains Unicode codepoints beyond
 578      that range. The file is best read with the functions in the Unicode
 579      aware `io(3)
 580      <javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__
 581      module. Bytes written to the file by any means are translated to UTF-8
 582      encoding before actually being stored on the disk file.
 583    :utf16 or {utf16,big}: Works like unicode, but translation is done to
 584      and from big endian UTF-16 instead of UTF-8.
 585    :{utf16,little}: Works like unicode, but translation is done to and
 586      from little endian UTF-16 instead of UTF-8.
 587    :utf32 or {utf32,big}: Works like unicode, but translation is done to
 588      and from big endian UTF-32 instead of UTF-8.
 589    :{utf32,little}: Works like unicode, but translation is done to and
 590      from little endian UTF-32 instead of UTF-8.
 591
 592The Encoding can be changed for a file "on the fly" by using the
 593  `io:setopts/2 <javascript:erlhref('../../../../',%20'stdlib',%20'io.ht
 594  ml#setopts-2');>`__ function, why a file can be analyzed in latin1
 595  encoding for i.e. a BOM, positioned beyond the BOM and then be set for
 596  the right encoding before further reading.See the `unicode(3)
 597  <javascript:erlhref('../../../../',%20'stdlib',%20'unicode.html');>`__
 598  module for functions identifying BOM's. This option is not allowed on
 599  raw files.
 600
 601
 602Returns:
 603
 604:{ok, IoDevice}: The file has been opened in the requested
 605  mode.IoDevice is a reference to the file.
 606:{error, Reason}: The file could not be opened.
 607
 608
 609IoDevice is really the pid of the process which handles the file. This
 610process is linked to the process which originally opened the file. If
 611any process to which the IoDevice is linked terminates, the file will
 612be closed and the process itself will be terminated. An IoDevice
 613returned from this call can be used as an argument to the IO functions
 614(see `io(3)
 615<javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__).
 616Note
 617In previous versions of file, modes were given as one of the atoms
 618read, write, orread_write instead of a list. This is still allowed for
 619reasons of backwards compatibility, but should not be used for new
 620code. Also note that read_write is not allowed in a mode list.
 621
 622Typical error reasons:
 623
 624:enoent: The file does not exist.
 625:eacces: Missing permission for reading the file or searching one of
 626  the parent directories.
 627:eisdir: The named file is not a regular file. It may be a directory,
 628  a fifo, or a device.
 629:enotdir: A component of the file name is not a directory. On some
 630  platforms, enoent is returned instead.
 631:enospc: There is a no space left on the device (if write access was
 632  specified).
 633
 634
 635path_consult(Path, Filename) -> {ok, Terms, FullName} | {error,
 636Reason}
 637
 638
 639Types:
 640
 641Path = [Dir]
 642�Dir = name()
 643Filename = name()
 644Terms = [term()]
 645FullName = string()
 646Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 647�Line, Mod, Term -- see below
 648
 649
 650Searches the path Path (a list of directory names) until the file
 651Filename is found. If Filename is an absolute filename, Path is
 652ignored. Then reads Erlang terms, separated by '.', from the file.
 653Returns one of the following:
 654
 655:{ok, Terms, FullName}: The file was successfully read. FullName is
 656  the full name of the file.
 657:{error, enoent}: The file could not be found in any of the
 658  directories inPath.
 659:{error, atom()}: An error occurred when opening the file or reading
 660  it. See open/2 for a list of typical error codes.
 661:{error, {Line, Mod, Term}}: An error occurred when interpreting the
 662  Erlang terms in the file. Use format_error/1 to convert the three-
 663  element tuple to an English description of the error.
 664
 665
 666path_eval(Path, Filename) -> {ok, FullName} | {error, Reason}
 667
 668
 669Types:
 670
 671Path = [Dir]
 672�Dir = name()
 673Filename = name()
 674FullName = string()
 675Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 676�Line, Mod, Term -- see below
 677
 678
 679Searches the path Path (a list of directory names) until the file
 680Filename is found. If Filename is an absolute file name, Path is
 681ignored. Then reads and evaluates Erlang expressions, separated by '.'
 682(or ',', a sequence of expressions is also an expression), from the
 683file. The actual result of evaluation is not returned; any expression
 684sequence in the file must be there for its side effect. Returns one of
 685the following:
 686
 687:{ok, FullName}: The file was read and evaluated. FullName is the full
 688  name of the file.
 689:{error, enoent}: The file could not be found in any of the
 690  directories inPath.
 691:{error, atom()}: An error occurred when opening the file or reading
 692  it. See open/2 for a list of typical error codes.
 693:{error, {Line, Mod, Term}}: An error occurred when interpreting the
 694  Erlang expressions in the file. Use format_error/1 to convert the
 695  three-element tuple to an English description of the error.
 696
 697
 698path_open(Path, Filename, Modes) -> {ok, IoDevice, FullName} | {error,
 699Reason}
 700
 701
 702Types:
 703
 704Path = [Dir]
 705�Dir = name()
 706Filename = name()
 707Modes = [Mode] -- see open/2
 708IoDevice = io_device()
 709FullName = string()
 710Reason = ext_posix() | system_limit
 711
 712
 713Searches the path Path (a list of directory names) until the file
 714Filename is found. If Filename is an absolute file name, Path is
 715ignored. Then opens the file in the mode determined by Modes. Returns
 716one of the following:
 717
 718:{ok, IoDevice, FullName}: The file has been opened in the requested
 719  mode.IoDevice is a reference to the file andFullName is the full name
 720  of the file.
 721:{error, enoent}: The file could not be found in any of the
 722  directories inPath.
 723:{error, atom()}: The file could not be opened.
 724
 725
 726path_script(Path, Filename) -> {ok, Value, FullName} | {error, Reason}
 727
 728
 729Types:
 730
 731Path = [Dir]
 732�Dir = name()
 733Filename = name()
 734Value = term()
 735FullName = string()
 736Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
 737�Line, Mod, Term -- see below
 738
 739
 740Searches the path Path (a list of directory names) until the file
 741Filename is found. If Filename is an absolute file name, Path is
 742ignored. Then reads and evaluates Erlang expressions, separated by '.'
 743(or ',', a sequence of expressions is also an expression), from the
 744file. Returns one of the following:
 745
 746:{ok, Value, FullName}: The file was read and evaluated. FullName is
 747  the full name of the file and Value the value of the last expression.
 748:{error, enoent}: The file could not be found in any of the
 749  directories inPath.
 750:{error, atom()}: An error occurred when opening the file or reading
 751  it. See open/2 for a list of typical error codes.
 752:{error, {Line, Mod, Term}}: An error occurred when interpreting the
 753  Erlang expressions in the file. Use format_error/1 to convert the
 754  three-element tuple to an English description of the error.
 755
 756
 757path_script(Path, Filename, Bindings) -> {ok, Value, FullName} |
 758{error, Reason}
 759
 760
 761Types:
 762
 763Path = [Dir]
 764�Dir = name()
 765Filename = name()
 766Bindings -- see erl_eval(3)
 767Value = term()
 768FullName = string()
 769Reason = posix() | terminated | system_limit | {Line, Mod, Term}
 770�Line, Mod, Term -- see path_script/2
 771
 772
 773The same as path_script/2 but the variable bindingsBindings are used
 774in the evaluation. See `erl_eval(3) <javascript:erlhref('../../../../'
 775,%20'stdlib',%20'erl_eval.html');>`__ about variable bindings.
 776
 777pid2name(Pid) -> string() | undefined
 778
 779
 780Types:
 781
 782Pid = pid()
 783
 784
 785If Pid is an IO device, that is, a pid returned fromopen/2, this
 786function returns the filename, or rather:
 787
 788:{ok, Filename}: If this node's file server is not a slave, the file
 789  was opened by this node's file server, (this implies thatPid must be a
 790  local pid) and the file is not closed. Filename is the filename in
 791  flat string format.
 792:undefined: In all other cases.
 793
 794Warning
 795This function is intended for debugging only.
 796
 797position(IoDevice, Location) -> {ok, NewPosition} | {error, Reason}
 798
 799
 800Types:
 801
 802IoDevice = io_device()
 803Location = Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} |
 804bof | cur | eof
 805�Offset = int()
 806NewPosition = int()
 807Reason = ext_posix() | terminated
 808
 809
 810Sets the position of the file referenced by IoDevice to Location.
 811Returns {ok, NewPosition} (as absolute offset) if successful,
 812otherwise{error, Reason}. Location is one of the following:
 813
 814:Offset: The same as {bof, Offset}.
 815:{bof, Offset}: Absolute offset.
 816:{cur, Offset}: Offset from the current position.
 817:{eof, Offset}: Offset from the end of file.
 818:bof | cur | eof: The same as above with Offset 0.
 819
 820
 821Note that offsets are counted in bytes, not in characters. If the file
 822is opened using some other encoding than latin1, one byte does not
 823correspond to one character. Positioning in such a file can only be
 824done to known character boundaries, i.e. to a position earlier
 825retrieved by getting a current position, to the beginning/end of the
 826file or to some other position known to be on a correct character
 827boundary by some other means (typically beyond a byte order mark in
 828the file, which has a known byte-size).
 829
 830Typical error reasons are:
 831
 832:einval: Either Location was illegal, or it evaluated to a negative
 833  offset in the file. Note that if the resulting position is a negative
 834  value, the result is an error, and after the call the file position is
 835  undefined.
 836
 837
 838pread(IoDevice, LocNums) -> {ok, DataL} | eof | {error, Reason}
 839
 840
 841Types:
 842
 843IoDevice = io_device()
 844LocNums = [{Location, Number}]
 845�Location -- see position/2
 846�Number = int()
 847DataL = [Data]
 848�Data = [char()] | binary()
 849Reason = ext_posix() | terminated
 850
 851
 852Performs a sequence of pread/3 in one operation, which is more
 853efficient than calling them one at a time. Returns {ok, [Data, ...]}
 854or {error, Reason}, where each Data, the result of the
 855correspondingpread, is either a list or a binary depending on the mode
 856of the file, or eof if the requested position was beyond end of file.
 857
 858As the position is given as a byte-offset, special caution has to be
 859taken when working with files where encoding is set to something else
 860than latin1, as not every byte position will be a valid character
 861boundary on such a file.
 862
 863pread(IoDevice, Location, Number) -> {ok, Data} | eof | {error,
 864Reason}
 865
 866
 867Types:
 868
 869IoDevice = io_device()
 870Location -- see position/2
 871Number = int()
 872Data = [char()] | binary()
 873Reason = ext_posix() | terminated
 874
 875
 876Combines position/2 and read/2 in one operation, which is more
 877efficient than calling them one at a time. If IoDevice has been opened
 878in raw mode, some restrictions apply: Location is only allowed to be
 879an integer; and the current position of the file is undefined after
 880the operation.
 881
 882As the position is given as a byte-offset, special caution has to be
 883taken when working with files where encoding is set to something else
 884than latin1, as not every byte position will be a valid character
 885boundary on such a file.
 886
 887pwrite(IoDevice, LocBytes) -> ok | {error, {N, Reason}}
 888
 889
 890Types:
 891
 892IoDevice = io_device()
 893LocBytes = [{Location, Bytes}]
 894�Location -- see position/2
 895�Bytes = iodata()
 896N = int()
 897Reason = ext_posix() | terminated
 898
 899
 900Performs a sequence of pwrite/3 in one operation, which is more
 901efficient than calling them one at a time. Returns ok or {error, {N,
 902Reason}}, whereN is the number of successful writes that was done
 903before the failure.
 904
 905When positioning in a file with other encoding than latin1, caution
 906must be taken to set the position on a correct character boundary, see
 907position/2 for details.
 908
 909pwrite(IoDevice, Location, Bytes) -> ok | {error, Reason}
 910
 911
 912Types:
 913
 914IoDevice = io_device()
 915Location -- see position/2
 916Bytes = iodata()
 917Reason = ext_posix() | terminated
 918
 919
 920Combines position/2 and write/2 in one operation, which is more
 921efficient than calling them one at a time. If IoDevice has been opened
 922in raw mode, some restrictions apply: Location is only allowed to be
 923an integer; and the current position of the file is undefined after
 924the operation.
 925
 926When positioning in a file with other encoding than latin1, caution
 927must be taken to set the position on a correct character boundary, see
 928position/2 for details.
 929
 930read(IoDevice, Number) -> {ok, Data} | eof | {error, Reason}
 931
 932
 933Types:
 934
 935IoDevice = io_device()
 936Number = int()
 937Data = [char()] | binary()
 938Reason = ext_posix() | terminated
 939
 940
 941Reads Number bytes/characters from the file referenced byIoDevice. The
 942functions read/2, pread/3 and read_line/1 are the only ways to read
 943from a file opened in raw mode (although they work for normally opened
 944files, too).
 945
 946For files where encoding is set to something else than latin1, one
 947character might be represented by more than one byte on the file. The
 948parameter Number always denotes the number of characters read from the
 949file, why the position in the file might be moved a lot more than this
 950number when reading a Unicode file.
 951
 952Also if encoding is set to something else than latin1, the read/3 call
 953will fail if the data contains characters larger than 255, why the
 954`io(3)
 955<javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__
 956module is to be preferred when reading such a file.
 957
 958The function returns:
 959
 960:{ok, Data}: If the file was opened in binary mode, the read bytes are
 961  returned in a binary, otherwise in a list. The list or binary will be
 962  shorter than the number of bytes requested if end of file was reached.
 963:eof: Returned if Number>0 and end of file was reached before anything
 964  at all could be read.
 965:{error, Reason}: An error occurred.
 966
 967
 968Typical error reasons:
 969
 970:ebadf: The file is not opened for reading.
 971:{no_translation, unicode, latin1}: The file is was opened with
 972  another encoding than latin1 and the data on the file can not be
 973  translated to the byte-oriented data that this function returns.
 974
 975
 976read_file(Filename) -> {ok, Binary} | {error, Reason}
 977
 978
 979Types:
 980
 981Filename = name()
 982Binary = binary()
 983Reason = ext_posix() | terminated | system_limit
 984
 985
 986Returns {ok, Binary}, where Binary is a binary data object that
 987contains the contents of Filename, or{error, Reason} if an error
 988occurs.
 989
 990Typical error reasons:
 991
 992:enoent: The file does not exist.
 993:eacces: Missing permission for reading the file, or for searching one
 994  of the parent directories.
 995:eisdir: The named file is a directory.
 996:enotdir: A component of the file name is not a directory. On some
 997  platforms, enoent is returned instead.
 998:enomem: There is not enough memory for the contents of the file.
 999
1000
1001read_file_info(Filename) -> {ok, FileInfo} | {error, Reason}
1002
1003
1004Types:
1005
1006Filename = name()
1007FileInfo = #file_info{}
1008Reason = ext_posix()
1009
1010
1011Retrieves information about a file. Returns{ok, FileInfo} if
1012successful, otherwise{error, Reason}. FileInfo is a recordfile_info,
1013defined in the Kernel include filefile.hrl. Include the following
1014directive in the module from which the function is called:
1015
1016
1017.. sourcecode:: erlang
1018
1019    
1020    -include_lib("kernel/include/file.hrl").
1021
1022
1023The record file_info contains the following fields.
1024
1025:size = int(): Size of file in bytes.
1026:type = device | directory | regular | other: The type of the file.
1027:access = read | write | read_write | none: The current system access
1028  to the file.
1029:atime = time(): The last (local) time the file was read.
1030:mtime = time(): The last (local) time the file was written.
1031:ctime = time(): The interpretation of this time field depends on the
1032  operating system. On Unix, it is the last time the file or the inode
1033  was changed. In Windows, it is the create time.
1034:mode = int(): The file permissions as the sum of the following bit
1035values:
1036    : 8#00400: read permission: owner
1037    : 8#00200: write permission: owner
1038    : 8#00100: execute permission: owner
1039    : 8#00040: read permission: group
1040    : 8#00020: write permission: group
1041    : 8#00010: execute permission: group
1042    : 8#00004: read permission: other
1043    : 8#00002: write permission: other
1044    : 8#00001: execute permission: other
1045    : 16#800: set user id on execution
1046    : 16#400: set group id on execution
1047
1048On Unix platforms, other bits than those listed above may be set.
1049:links = int(): Number of links to the file (this will always be 1 for
1050  file systems which have no concept of links).
1051:major_device = int(): Identifies the file system where the file is
1052  located. In Windows, the number indicates a drive as follows: 0 means
1053  A:, 1 means B:, and so on.
1054:minor_device = int(): Only valid for character devices on Unix. In
1055  all other cases, this field is zero.
1056:inode = int(): Gives the inode number. On non-Unix file systems, this
1057  field will be zero.
1058:uid = int(): Indicates the owner of the file. Will be zero for non-
1059  Unix file systems.
1060:gid = int(): Gives the group that the owner of the file belongs to.
1061  Will be zero for non-Unix file systems.
1062
1063
1064Typical error reasons:
1065
1066:eacces: Missing search permission for one of the parent directories
1067  of the file.
1068:enoent: The file does not exist.
1069:enotdir: A component of the file name is not a directory. On some
1070  platforms, enoent is returned instead.
1071
1072
1073read_line(IoDevice) -> {ok, Data} | eof | {error, Reason}
1074
1075
1076Types:
1077
1078IoDevice = io_device()
1079Data = [char()] | binary()
1080Reason = ext_posix() | terminated
1081
1082
1083Reads a line of bytes/characters from the file referenced byIoDevice.
1084Lines are defined to be delimited by the linefeed (LF, \n) character,
1085but any carriage return (CR, \r) followed by a newline is also treated
1086as a single LF character (the carriage return is silently ignored).
1087The line is returned including the LF, but excluding any CR
1088immediately followed by a LF. This behaviour is consistent with the
1089behaviour of `io:get_line/2 <javascript:erlhref('../../../../',%20'std
1090lib',%20'io.html#get_line-2');>`__. If end of file is reached without
1091any LF ending the last line, a line with no trailing LF is returned.
1092
1093The function can be used on files opened in raw mode. It is however
1094inefficient to use it on raw files if the file is not opened with the
1095option {read_ahead, Size} specified, why combining raw and
1096{read_ahead, Size} is highly recommended when opening a text file for
1097raw line oriented reading.
1098
1099If encoding is set to something else than latin1, the read_line/1 call
1100will fail if the data contains characters larger than 255, why the
1101`io(3)
1102<javascript:erlhref('../../../../',%20'stdlib',%20'io.html');>`__
1103module is to be preferred when reading such a file.
1104
1105The function returns:
1106
1107:{ok, Data}: One line from the file is returned, including the
1108  trailing LF, but with CRLF sequences replaced by a single LF (see
1109  above). If the file was opened in binary mode, the read bytes are
1110  returned in a binary, otherwise in a list.
1111:eof: Returned if end of file was reached before anything at all could
1112  be read.
1113:{error, Reason}: An error occurred.
1114
1115
1116Typical error reasons:
1117
1118:ebadf: The file is not opened for reading.
1119:{no_translation, unicode, latin1}: The file is was opened with
1120  another encoding than latin1 and the data on the file can not be
1121  translated to the byte-oriented data that this function returns.
1122
1123
1124read_link(Name) -> {ok, Filename} | {error, Reason}
1125
1126
1127Types:
1128
1129Name = name()
1130Filename = string()
1131Reason = ext_posix()
1132
1133
1134This function returns {ok, Filename} if Name refers to a symbolic link
1135or {error, Reason} otherwise. On platforms that do not support
1136symbolic links, the return value will be {error,enotsup}.
1137
1138Typical error reasons:
1139
1140:einval: Linkname does not refer to a symbolic link.
1141:enoent: The file does not exist.
1142:enotsup: Symbolic links are not supported on this platform.
1143
1144
1145read_link_info(Name) -> {ok, FileInfo} | {error, Reason}
1146
1147
1148Types:
1149
1150Name = name()
1151FileInfo = #file_info{}, see read_file_info/1
1152Reason = ext_posix()
1153
1154
1155This function works like read_file_info/1, except that if Name is a
1156symbolic link, information about the link will be returned in the
1157file_info record and the type field of the record will be set
1158tosymlink.
1159
1160If Name is not a symbolic link, this function returns exactly the same
1161result as read_file_info/1. On platforms that do not support symbolic
1162links, this function is always equivalent to read_file_info/1.
1163
1164rename(Source, Destination) -> ok | {error, Reason}
1165
1166
1167Types:
1168
1169Source = Destination = name()
1170Reason = ext_posix()
1171
1172
1173Tries to rename the file Source to Destination. It can be used to move
1174files (and directories) between directories, but it is not sufficient
1175to specify the destination only. The destination file name must also
1176be specified. For example, if bar is a normal file andfoo and baz are
1177directories,rename("foo/bar", "baz") returns an error,
1178butrename("foo/bar", "baz/bar") succeeds. Returnsok if it is
1179successful.
1180Note
1181Renaming of open files is not allowed on most platforms (see eacces
1182below).
1183
1184Typical error reasons:
1185
1186:eacces: Missing read or write permissions for the parent directories
1187  of Source or Destination. On some platforms, this error is given if
1188  eitherSource or Destination is open.
1189:eexist: Destination is not an empty directory. On some platforms,
1190  also given when Source andDestination are not of the same type.
1191:einval: Source is a root directory, or Destination is a sub-directory
1192  of Source.
1193:eisdir: Destination is a directory, but Source is not.
1194:enoent: Source does not exist.
1195:enotdir: Source is a directory, but Destination is not.
1196:exdev: Source and Destination are on different file systems.
1197
1198
1199script(Filename) -> {ok, Value} | {error, Reason}
1200
1201
1202Types:
1203
1204Filename = name()
1205Value = term()
1206Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
1207�Line, Mod, Term -- see below
1208
1209
1210Reads and evaluates Erlang expressions, separated by '.' (or ',', a
1211sequence of expressions is also an expression), from the file. Returns
1212one of the following:
1213
1214:{ok, Value}: The file was read and evaluated. Value is the value of
1215  the last expression.
1216:{error, atom()}: An error occurred when opening the file or reading
1217  it. See open/2 for a list of typical error codes.
1218:{error, {Line, Mod, Term}}: An error occurred when interpreting the
1219  Erlang expressions in the file. Use format_error/1 to convert the
1220  three-element tuple to an English description of the error.
1221
1222
1223script(Filename, Bindings) -> {ok, Value} | {error, Reason}
1224
1225
1226Types:
1227
1228Filename = name()
1229Bindings -- see erl_eval(3)
1230Value = term()
1231Reason = ext_posix() | terminated | system_limit | {Line, Mod, Term}
1232�Line, Mod, Term -- see below
1233
1234
1235The same as script/1 but the variable bindingsBindings are used in the
1236evaluation. See `erl_eval(3) <javascript:erlhref('../../../../',%20'st
1237dlib',%20'erl_eval.html');>`__ about variable bindings.
1238
1239set_cwd(Dir) -> ok | {error,Reason}
1240
1241
1242Types:
1243
1244Dir = name()
1245Reason = ext_posix()
1246
1247
1248Sets the current working directory of the file server toDir. Returns
1249ok if successful.
1250
1251Typical error reasons are:
1252
1253:enoent: The directory does not exist.
1254:enotdir: A component of Dir is not a directory. On some platforms,
1255  enoent is returned.
1256:eacces: Missing permission for the directory or one of its parents.
1257:badarg: Filename had an improper type, such as tuple.
1258
1259Warning
1260In a future release, a bad type for the Filename argument will
1261probably generate an exception.
1262
1263
1264
1265sync(IoDevice) -> ok | {error, Reason}
1266
1267
1268Types:
1269
1270IoDevice = io_device()
1271Reason = ext_posix() | terminated
1272
1273
1274Makes sure that any buffers kept by the operating system (not by the
1275Erlang runtime system) are written to disk. On some platforms, this
1276function might have no effect.
1277
1278Typical error reasons are:
1279
1280:enospc: Not enough space left to write the file.
1281
1282
1283truncate(IoDevice) -> ok | {error, Reason}
1284
1285
1286Types:
1287
1288IoDevice = io_device()
1289Reason = ext_posix() | terminated
1290
1291
1292Truncates the file referenced by IoDevice at the current position.
1293Returns ok if successful, otherwise {error, Reason}.
1294
1295write(IoDevice, Bytes) -> ok | {error, Reason}
1296
1297
1298Types:
1299
1300IoDevice = io_device()
1301Bytes = iodata()
1302Reason = ext_posix() | terminated
1303
1304
1305Writes Bytes to the file referenced byIoDevice. This function is the
1306only way to write to a file opened in raw mode (although it works for
1307normally opened files, too). Returns ok if successful, and{error,
1308Reason} otherwise.
1309
1310If the file is opened with encoding set to something else than latin1,
1311each byte written might result in several bytes actually being written
1312to the file, as the byte range 0..255 might represent anything between
1313one and four bytes depending on value and UTF encoding type.
1314
1315Typical error reasons are:
1316
1317:ebadf: The file is not opened for writing.
1318:enospc: There is a no space left on the device.
1319
1320
1321write_file(Filename, Bytes) -> ok | {error, Reason}
1322
1323
1324Types:
1325
1326Filename = name()
1327Bytes = iodata()
1328Reason = ext_posix() | terminated | system_limit
1329
1330
1331Writes the contents of the iodata term Bytes to the file Filename. The
1332file is created if it does not exist. If it exists, the previous
1333contents are overwritten. Returns ok, or {error, Reason}.
1334
1335Typical error reasons are:
1336
1337:enoent: A component of the file name does not exist.
1338:enotdir: A component of the file name is not a directory. On some
1339  platforms, enoent is returned instead.
1340:enospc: There is a no space left on the device.
1341:eacces: Missing permission for writing the file or searching one of
1342  the parent directories.
1343:eisdir: The named file is a directory.
1344
1345
1346write_file(Filename, Bytes, Modes) -> ok | {error, Reason}
1347
1348
1349Types:
1350
1351Filename = name()
1352Bytes = iodata()
1353Modes = [Mode] -- see open/2
1354Reason = ext_posix() | terminated | system_limit
1355
1356
1357Same as write_file/2, but takes a third argumentModes, a list of
1358possible modes, seeopen/2. The mode flagsbinary and write are
1359implicit, so they should not be used.
1360
1361write_file_info(Filename, FileInfo) -> ok | {error, Reason}
1362
1363
1364Types:
1365
1366Filename = name()
1367FileInfo = #file_info{} -- see also read_file_info/1
1368Reason = ext_posix()
1369
1370
1371Change file information. Returns ok if successful, otherwise {error,
1372Reason}. FileInfo is a recordfile_info, defined in the Kernel include
1373filefile.hrl. Include the following directive in the module from which
1374the function is called:
1375
1376
1377.. sourcecode:: erlang
1378
1379    
1380    -include_lib("kernel/include/file.hrl").
1381
1382
1383The following fields are used from the record, if they are given.
1384
1385:atime = time(): The last (local) time the file was read.
1386:mtime = time(): The last (local) time the file was written.
1387:ctime = time(): On Unix, any value give for this field will be
1388  ignored (the "ctime" for the file will be set to the current time). On
1389  Windows, this field is the new creation time to set for the file.
1390:mode = int(): The file permissions as the sum of the following bit
1391values:
1392    : 8#00400: read permission: owner
1393    : 8#00200: write permission: owner
1394    : 8#00100: execute permission: owner
1395    : 8#00040: read permission: group
1396    : 8#00020: write permission: group
1397    : 8#00010: execute permission: group
1398    : 8#00004: read permission: other
1399    : 8#00002: write permission: other
1400    : 8#00001: execute permission: other
1401    : 16#800: set user id on execution
1402    : 16#400: set group id on execution
1403
1404On Unix platforms, other bits than those listed above may be set.
1405:uid = int(): Indicates the owner of the file. Ignored for non-Unix
1406  file systems.
1407:gid = int(): Gives the group that the owner of the file belongs to.
1408  Ignored non-Unix file systems.
1409
1410
1411Typical error reasons:
1412
1413:eacces: Missing search permission for one of the parent directories
1414  of the file.
1415:enoent: The file does not exist.
1416:enotdir: A component of the file name is not a directory. On some
1417  platforms, enoent is returned instead.
1418
1419
1420
1421
1422POSIX Error Codes
1423~~~~~~~~~~~~~~~~~
1424
1425
1426+ eacces - permission denied
1427+ eagain - resource temporarily unavailable
1428+ ebadf - bad file number
1429+ ebusy - file busy
1430+ edquot - disk quota exceeded
1431+ eexist - file already exists
1432+ efault - bad address in system call argument
1433+ efbig - file too large
1434+ eintr - interrupted system call
1435+ einval - invalid argument
1436+ eio - IO error
1437+ eisdir - illegal operation on a directory
1438+ eloop - too many levels of symbolic links
1439+ emfile - too many open files
1440+ emlink - too many links
1441+ enametoolong - file name too long
1442+ enfile - file table overflow
1443+ enodev - no such device
1444+ enoent - no such file or directory
1445+ enomem - not enough memory
1446+ enospc - no space left on device
1447+ enotblk - block device required
1448+ enotdir - not a directory
1449+ enotsup - operation not supported
1450+ enxio - no such device or address
1451+ eperm - not owner
1452+ epipe - broken pipe
1453+ erofs - read-only file system
1454+ espipe - invalid seek
1455+ esrch - no such process
1456+ estale - stale remote file handle
1457+ exdev - cross-domain link
1458
1459
1460
1461
1462Performance
1463~~~~~~~~~~~
1464
1465Some operating system file operations, for example async/1 or close/1
1466on a huge file, may block their calling thread for seconds. If this
1467befalls the emulator main thread, the response time is no longer in
1468the order of milliseconds, depending on the definition of "soft" in
1469soft real-time system.
1470
1471If the device driver thread pool is active, file operations are done
1472through those threads instead, so the emulator can go on executing
1473Erlang processes. Unfortunately, the time for serving a file operation
1474increases due to the extra scheduling required from the operating
1475system.
1476
1477If the device driver thread pool is disabled or of size 0, large file
1478reads and writes are segmented into several smaller, which enables the
1479emulator so server other processes during the file operation. This
1480gives the same effect as when using the thread pool, but with larger
1481overhead. Other file operations, for example sync/1 or close/1 on a
1482huge file, still are a problem.
1483
1484For increased performance, raw files are recommended. Raw files uses
1485the file system of the node's host machine. For normal files (non-
1486raw), the file server is used to find the files, and if the node is
1487running its file server as slave to another node's, and the other node
1488runs on some other host machine, they may have different file systems.
1489This is seldom a problem, but you have now been warned.
1490
1491A normal file is really a process so it can be used as an IO device
1492(see io). Therefore when data is written to a normal file, the sending
1493of the data to the file process, copies all data that are not
1494binaries. Opening the file in binary mode and writing binaries is
1495therefore recommended. If the file is opened on another node, or if
1496the file server runs as slave to another node's, also binaries are
1497copied.
1498
1499Caching data to reduce the number of file operations, or rather the
1500number of calls to the file driver, will generally increase
1501performance. The following function writes 4 MBytes in 23 seconds when
1502tested:
1503
1504
1505.. sourcecode:: erlang
1506
1507    
1508    create_file_slow(Name, N) when integer(N), N >= 0 ->
1509        {ok, FD} = file:open(Name, [raw, write, delayed_write, binary]),
1510        ok = create_file_slow(FD, 0, N),
1511        ok = ?FILE_MODULE:close(FD),
1512        ok.
1513          
1514    create_file_slow(FD, M, M) ->
1515        ok;
1516    create_file_slow(FD, M, N) ->
1517        ok = file:write(FD, <<M:32/unsigned>>),
1518        create_file_slow(FD, M+1, N).
1519
1520
1521The following, functionally equivalent, function collects 1024 entries
1522into a list of 128 32-byte binaries before each call tofile:write/2
1523and so does the same work in 0.52 seconds, which is 44 times faster.
1524
1525
1526.. sourcecode:: erlang
1527
1528    
1529    create_file(Name, N) when integer(N), N >= 0 ->
1530        {ok, FD} = file:open(Name, [raw, write, delayed_write, binary]),
1531        ok = create_file(FD, 0, N),
1532        ok = ?FILE_MODULE:close(FD),
1533        ok.
1534          
1535    create_file(FD, M, M) ->
1536        ok;
1537    create_file(FD, M, N) when M + 1024 =< N ->
1538        create_file(FD, M, M + 1024, []),
1539        create_file(FD, M + 1024, N);
1540    create_file(FD, M, N) ->
1541        create_file(FD, M, N, []).
1542          
1543    create_file(FD, M, M, R) ->
1544        ok = file:write(FD, R);
1545    create_file(FD, M, N0, R) when M + 8 =< N0 ->
1546        N1  = N0-1,  N2  = N0-2,  N3  = N0-3,  N4  = N0-4, 
1547        N5  = N0-5,  N6  = N0-6,  N7  = N0-7,  N8  = N0-8, 
1548        create_file(FD, M, N8, 
1549                    [<<N8:32/unsigned,  N7:32/unsigned, 
1550                       N6:32/unsigned,  N5:32/unsigned, 
1551                       N4:32/unsigned,  N3:32/unsigned, 
1552                       N2:32/unsigned,  N1:32/unsigned>> | R]);
1553    create_file(FD, M, N0, R) ->
1554        N1 = N0-1,
1555        create_file(FD, M, N1, [<<N1:32/unsigned>> | R]).
1556
1557Note
1558Trust only your own benchmarks. If the list length in create_file/2
1559above is increased, it will run slightly faster, but consume more
1560memory and cause more memory fragmentation. How much this affects your
1561application is something that this simple benchmark can not predict.
1562
1563If the size of each binary is increased to 64 bytes, it will also run
1564slightly faster, but the code will be twice as clumsy. In the current
1565implementation are binaries larger than 64 bytes stored in memory
1566common to all processes and not copied when sent between processes,
1567while these smaller binaries are stored on the process heap and copied
1568when sent like any other term.
1569
1570So, with a binary size of 68 bytes create_file/2 runs 30 percent
1571slower then with 64 bytes, and will cause much more memory
1572fragmentation. Note that if the binaries were to be sent between
1573processes (for example a non-raw file) the results would probably be
1574completely different.
1575
1576A raw file is really a port. When writing data to a port, it is
1577efficient to write a list of binaries. There is no need to flatten a
1578deep list before writing. On Unix hosts, scatter output, which writes
1579a set of buffers in one operation, is used when possible. In this way
1580file:write(FD, [Bin1, Bin2 | Bin3]) will write the contents of the
1581binaries without copying the data at all except for perhaps deep down
1582in the operating syste…

Large files files are truncated, but you can click here to view the full file