# io

### MODULE

io

### MODULE SUMMARY

Standard I/O Server Interface Functions

### DESCRIPTION

This module provides an interface to standard Erlang IO servers. The output functions all return `ok` if they are successful, or exit if they are not. In the following description, a parameter within square brackets means that that parameter is optional. `[IoDevice,]` is such an example. If included, it must be the Pid of a process which handles the IO protocols. This is often the `IoDevice` returned by `file:open/2` (see `file`). For a description of the I/O protocols refer to Armstrong, Virding and Williams, 'Concurrent Programming in Erlang', Chapter 13, unfortunately now very outdated, but the general principles still apply.

### EXPORTS

`put_chars([IoDevice,] Chars)`

Writes the characters `Chars` to the standard output (`IoDevice`). `Chars` is a list of characters. The list is not necessarily flat.

`nl([IoDevice])`

Writes new line to the standard output (`IoDevice`).

`get_chars([IoDevice,] Prompt, Count)`

Gets `Count` characters from standard input (`IoDevice`), prompting it with `Prompt`. It returns:

`ListOfChars`
  Returns the input characters, if they are less than `Count`.
`eof`
  End of file was encountered.

`get_line([IoDevice,] Prompt)`

Gets a line from the standard input (`IoDevice`), prompting it with `Prompt`. It returns:

`ListOfChars`
  The characters in the line terminated by a LF unless the line read was the last line of the file and was not terminated by LF.
`eof`
  End of file was encountered.

`setopts([IoDevice,] OptList)`

Set options for standard input/output (`IoDevice`). Possible options are:

`binary`
  Makes `get_chars/2,3` and `get_line/1,2` return binaries instead of lists of chars.
`list`
  Makes `get_chars/2,3` and `get_line/1,2` return lists of chars, which is the default.

Returns `ok` if succesful or `{error,Reason}` if not.

| The `binary` option does not work against I/O servers on remote nodes running an older version of Erlang/OTP than R9C.

`write([IoDevice,] Term)`

Writes the term `Term` to the standard output (`IoDevice`).

`read([IoDevice,] Prompt)`

Reads a term from the standard input (`IoDevice`), prompting it with `Prompt`. It returns:

`{ok, Term}`
  The parsing was successful.
`{error, ErrorInfo}`
  The parsing failed.
`eof`
  End of file was encountered.

`fwrite(Format)`
`format(Format)`

Equivalent to `fwrite(Format, [])`.

`fwrite([IoDevice,] Format, Arguments)`
`format([IoDevice,] Format, Arguments)`

Writes the list of items in `Arguments` on the standard output (`IoDevice`) in accordance with `Format`. `Format` is a list of plain characters which are copied to the output device, and control sequences which cause the arguments to be printed. If `Format` is an atom, it is first converted to a list with the aid of `atom_to_list/1`. `Arguments` is the list of items to be printed.

    > io:fwrite("Hello world!~n", []).
    Hello world
    ok

The general format of a control sequence is `~F.P.PadC`. The character `C` determines the type of control sequence to be used, `F` and `P` are optional numeric arguments. If `F`, `P`, or `Pad` is `*`, the next argument in `Arguments` is used as the numeric value of `F` or `P`.

`F` is the `field width` of the printed argument. A negative value means that the argument will be left justified within the field, otherwise it will be right justified. If no field width is specified, the required print width will be used. If the field width specified is too small, then the whole field will be filled with `*` characters.

`P` is the `precision` of the printed argument. A default value is used if no precision is specified. The interpretation of precision depends on the control sequences. Unless otherwise specified, the argument `within` is used to determine print width.

`Pad` is the padding character. This is the character used to pad the printed representation of the argument so that it conforms to the specified field width and precision. Only one padding character can be specified and, whenever applicable, it is used for both the field width and precision. The default padding character is `' '` (space).

The following control sequences are available:

`~`
  The character `~` is written.
`c`
  The argument is a number that will be interpreted as an ASCII code. The precision is the number of times the character is printed and it defaults to the field width, which in turn defaults to one. The following example illustrates:

      > io:fwrite("|~10.5c|~-10.5c|~5c|~n", [$a, $b, $c]).
      |     aaaaa|aaaaa     |ccccc|
      ok

`f`
  The argument is a float which is written as `[-]ddd.ddd`, where the precision is the number of digits after the decimal point. The default precision is 6.
`e`
  The argument is a float which is written as `[-]d.ddde+-ddd`, where the precision is the number of digits written. The default precision is 6.
`g`
  The argument is a float which is written as `f`, if it is > 0.1, and < 10^4. Otherwise, it is written as `e`. The precision is the number of significant digits. It defaults to 6. There must always be a sufficient number of digits for printing a correct floating point representation of the argument.
`s`
  Prints the argument with the `string` syntax. The argument is a list of character codes (possibly not a flat list), or an atom. The characters are printed without quotes. In this format, the printed argument is truncated to the given precision and field width.
  This format can be used for printing any object and truncating the output so it fits a specified field:

      > io:fwrite("|~10w|~n", [{hey, hey, hey}]).
      |**********|
      ok
      > io:fwrite("|~10s|~n", [io_lib:write({hey, hey, hey})]).
      |{hey, hey, h|
      ok

`w`
  Writes data with the standard syntax. This is used to output Erlang terms. Atoms are printed within quotes if they contain embedded non-printable characters, and floats are printed in the default `g` format.
`p`
  Writes the data with standard syntax in the same way as `~w`, but breaks terms whose printed representation is longer than one line into many lines and indents each line sensibly. It also tries to detect lists of printable characters and to output these as strings. For example:

      > T = [{attributes,[[{id,age,1.50000},{mode,explicit},
             {typename,"INTEGER"}],
             [{id,cho},{mode,explicit},{typename,'Cho'}]]},
             {typename,'Person'},{tag,{'PRIVATE',3}},
             {mode,implicit}].
      ...
      > io:fwrite("~w~n", [T]).
      [{attributes,[[{id,age,1.50000},{mode,explicit},{typename,
      [73,78,84,69,71,69,82]}],[{id,cho},{mode,explicit},{typena
      me,'Cho'}]]},{typename,'Person'},{tag,{'PRIVATE',3}},{mode
      ,implicit}]
      ok
      > io:fwrite("~p~n", [T]).
      [{attributes,[[{id,age,1.50000},
                     {mode,explicit},
                     {typename,"INTEGER"}],
                    [{id,cho},{mode,explicit},{typename,'Cho'}]]},
       {typename,'Person'},
       {tag,{'PRIVATE',3}},
       {mode,implicit}]
      ok

  The field width specifies the maximum line length. It defaults to 80. The precision specifies the initial indentation of the term. It defaults to the number of characters printed on this line in the `same` call to `io:fwrite` or `io:format`. For example, using `T` above:

      > io:fwrite("Here T = ~p~n", [T]).
      Here T = [{attributes,[[{id,age,1.50000},
                              {mode,explicit},
                              {typename,"INTEGER"}],
                             [{id,cho},{mode,explicit},
                              {typename,'Cho'}]]},
                {typename,'Person'},
                {tag,{'PRIVATE',3}},
                {mode,implicit}]
      ok

`W`
  Writes data in the same way as `~w`, but takes an extra argument which is the maximum depth to which terms are printed. Anything below this depth is replaced with `...`. For example, using `T` above:

      > io:fwrite("~W~n", [T,9]).
      [{attributes,[[{id,age,1.50000},{mode,explicit},{typename|
      ...}],[{id,cho},{mode|...},{...}]]},{typename,'Person'},{t
      ag,{'PRIVATE',3}},{mode,implicit}]
      ok

  If the maximum depth has been reached, then it is impossible to read in the resultant output. Also, the `|...` form in a tuple denotes that there are more elements in the tuple but these are below the print depth.
`P`
  Writes data in the same way as `~p`, but takes an extra argument which is the maximum depth to which terms are printed. Anything below this depth is replaced with `...`. For example:

      > io:fwrite("~P~n", [T,9]).
      [{attributes,[[{id,age,1.50000},{mode,explicit},
                     {typename|...}],
                    [{id,cho},{mode|...},{...}]]},
       {typename,'Person'},
       {tag,{'PRIVATE',3}},
       {mode,implicit}]
      ok

`B`
  Writes an integer in base 2..36, the default base is 10. A leading dash is printed for negative integers.
  The precision field selects base. For example:

      >io:format("~.16B~n", [31]).
      1F
      ok
      >io:format("~.2B~n", [-19]).
      -10011
      ok
      >io:format("~.36B~n", [5*36+35]).
      5Z
      ok

`X`
  Like `B`, but takes an extra argument that is a prefix to insert before the number, but after the leading dash, if any.
  The prefix can be a possibly deep list of character codes or an atom.

      >io:format("~X~n", [31,"10#"]).
      10#31
      ok
      >io:format("~.16X~n", [-31,"0x"]).
      -0x1F
      ok

`#`
  Like `B`, but prints the number with an Erlang style '#'-separated base prefix.

      >io:format("~.10#~n", [31]).
      10#31
      ok
      >io:format("~.16X~n", [-31]).
      -16#1F
      ok

`b`
  Like `B`, but prints lowercase letters.
`x`
  Like `X`, but prints lowercase letters.
`+`
  Like `#`, but prints lowercase letters.
`n`
  Writes a new line.
`i`
  Ignores the next term.

Returns:

`ok`
  The formatting succeeded.

If an error occurs, there is no output. For example:

    > io:fwrite("~s ~w ~i ~w ~c ~n",['abc def', 'abc def',
                                     {foo, 1},{foo, 1}, 65]).
    abc def 'abc def'  {foo, 1} A
    ok
    > io:fwrite("~s", [65]).
    ** exited: {badarg,[{io,format,[<0.20.0>,"~s","A"]},
                        {erl_eval,expr,4},
                        {shell,eval_loop,2}]} **

In this example, an attempt was made to output the single character '65' with the aid of the string formatting directive "~s".

The two functions `fwrite` and `format` are identical. The old name `format` has been retained for backwards compatibility, while the new name `fwrite` has been added as a logical complement to `fread`.

`fread([IoDevice,] Prompt, Format)`

Reads characters from the standard input (`IoDevice`), prompting it with `Prompt`. Interprets the characters in accordance with `Format`. `Format` is a list of control sequences which directs the interpretation of the input.

`Format` may contain:

- White space characters (SPACE, TAB and NEWLINE) which cause input to be read to the next non-white space character.
- Ordinary characters which must match the next input character.
- Control sequences, which have the general format `~*FC`. The character `*` is an optional return suppression character. It provides a method to specify a field which is to be omitted. `F` is the `field width` of the input field and `C` determines the type of control sequence.
  Unless otherwise specified, leading white-space is ignored for all control sequences. An input field cannot be more than one line wide. The following control sequences are available:
  `~`
    A single `~` is expected in the input.
  `d`
    A decimal integer is expected.
  `u`
    An unsigned integer in base 2..36 is expected. The field width parameter is used to specify base. Leading white-space characters are not skipped.
  `-`
    An optional sign character is expected. A sign character '-' gives the return value `-1`. Sign character '+' or none gives `1`. The field width parameter is ignored. Leading white-space characters are not skipped.
  `#`
    An integer in base 2..36 with Erlang-style base prefix (for example `"16#ffff"`) is expected.
  `f`
    A floating point number is expected. It must follow the Erlang floating point number syntax.
  `s`
    A string of non-white-space characters is read. If a field width has been specified, this number of characters are read and all trailing white-space characters are stripped. An Erlang string (list of characters) is returned.
  `a`
    Similar to `s`, but the resulting string is converted into an atom.
  `c`
    The number of characters equal to the field width are read (default is 1) and returned as an Erlang string. However, leading and trailing white-space characters are not omitted as they are with `s`. All characters are returned.
  `l`
    Returns the number of characters which have been scanned up to that point, including white-space characters.
  It returns:
  `{ok, InputList}`
    The read was successful and `InputList` is the list of successfully matched and read items.
  `{error, What}`
    The read operation failed and the parameter `What` can be used as argument to `report_error/1` to produce an error message.
  `eof`
    End of file was encountered.

Examples:

    > io:fread('enter>', "~f~f~f").
    enter>1.9 35.5e3 15.0
    {ok, [1.90000, 3.55000e+4, 15.0000]}
    > io:fread('enter>', "~10f~d").
    enter>     5.67899
    {ok, [5.67800, 99]}
    > io:fread('enter>', ":~10s:~10c:").
    enter>:   alan  :   joe   :
    {ok, ["alan", "   joe    "]}

`scan_erl_exprs(Prompt)`
`scan_erl_exprs([IoDevice,] Prompt, StartLine)`

Reads data from the standard input (`IoDevice`), prompting it with `Prompt`. Reading starts at line number `StartLine` (1). The data is tokenized as if it were a sequence of Erlang expressions until a final `'.'` is reached. This token is also returned. It returns:

`{ok, Tokens, EndLine}`
  The tokenization succeeded.
`{error, ErrorInfo, EndLine}`
  An error occurred.
`{eof, EndLine}`
  End of file was encountered.

Example:

    > io:scan_erl_exprs('enter>').
    enter>abc(), "hey".
    {ok,[{atom, 1, abc},{'(', 1}, {')', 1}, {', ', 1},
        {string, 1, "hey"}, {dot, 1}], 2}
    > io:scan_erl_exprs('enter>').
    enter>1.0er.
    {error, {1, erl_scan, float}, 2}

`scan_erl_form(Prompt)`
`scan_erl_form(IoDevice, Prompt[, StartLine])`

Reads data from the standard input (`IoDevice`), prompting it with `Prompt`. Starts reading at line number `StartLine` (1). The data is tokenized as if it were an Erlang form - one of the valid Erlang expressions in an Erlang source file - until a final `'.'` is reached. This last token is also returned. The return values are the same as for `scan_erl_exprs`.

`parse_erl_exprs(Prompt)`
`parse_erl_exprs(IoDevice, Prompt[, StartLine])`

Reads data from the standard input (`IoDevice`), prompting it with `Prompt`. Starts reading at line number `StartLine` (1). The data is tokenized and parsed as if it were a sequence of Erlang expressions until a final `'.'` is reached. It returns:

`{ok, ExpressionList, EndLine}`
  The parsing was successful.
`{error, ErrorInfo, EndLine}`
  An error occurred.
`{eof, EndLine}`
  End of file was encountered.

Example:

    > io:parse_erl_exprs('enter>').
    enter>abc(), "hey".
    {ok, [{call, 1, [], abc, []}, {string, 1, "hey"}], 2}
    > io:parse_erl_exprs ('enter>').
    enter>abc("hey".
    {error, {1, erl_parse, {before, {terminator,') '}, {dot, 1}}}, 2}

`parse_erl_form(Prompt)`
`parse_erl_form(IoDevice, Prompt[, StartLine])`

Reads data from the standard input (`IoDevice`), prompting it with `Prompt` Starts reading at line number `StartLine` (1). The data is tokenized and parsed as if it were an Erlang form - one of the valid Erlang expressions in an Erlang source file - until a final `'.'` is reached. It returns:

`{ok, Form, EndLine}`
  The parsing was successful.
`{error, ErrorInfo, EndLine}`
  An error occurred.
`{eof, EndLine}`
  End of file was encountered.

### Standard Input/Output

All Erlang processes have a default standard IO device. This device is used when no `IoDevice` argument is specified in the IO calls. However, it is sometimes desirable to use an explicit `IoDevice` argument which refers to the default IO device. This is the case with functions that can access either a file or the default IO device. The atom `standard_io` has this special meaning. The following example illustrates this:

      > io:read('enter>').
      enter>foo.
      {term, foo}
      > io:read(standard_io, 'enter>').
      enter>bar.
      {term, bar}

There is always a process registered under the name of `user`. This can be used for sending output to the user.

### Error Information

The `ErrorInfo` mentioned above is the standard `ErrorInfo` structure which is returned from all IO modules. It has the following format:

        {ErrorLine, Module, ErrorDescriptor}

A string which describes the error is obtained with the following call:

    apply(Module, format_error, ErrorDescriptor)

### AUTHORS

Robert Virding - support@erlang.ericsson.se

stdlib 1.12
Copyright © 1991-2003 Ericsson Utvecklings AB