io(3erl)

๐Ÿ“ฆ
version 25.3.2.8 ยท 5 versions
, in ubuntu noble

๐Ÿ’– NAME ๐Ÿ’–

okay so bestie, this page is io(3erl) โ€” the manual for Standard I/O server interface functions. Itโ€™s giving โ€œyour whole standard Erlang I/O era,โ€ and weโ€™re gonna get into all of it. โœจ


โœจ DESCRIPTION โœจ

This module is literally your interface to standard Erlang I/O servers. The output functions all return ok if theyโ€™re successful, or exit if theyโ€™re not. periodt. ๐Ÿ’…

Every function in this module has an optional parameter IoDevice. If you include it, it must be the pid of a process that handles the I/O protocols. Normally, itโ€™s a IoDevice returned by file:open/2. If no IoDevice is given, standard_io is used โ€” thatโ€™s the default, no cap. ๐Ÿซถ

For a description of the I/O protocols, see section The Erlang I/O Protocol in the Userโ€™s Guide.

๐Ÿšจ Warning: ๐Ÿšจ

As from Erlang/OTP R13A, data supplied to function put_chars/2 is to be in the unicode:chardata() format. This means that programs supplying binaries to this function must convert them to UTF-8 before trying to output the data on an I/O device.
If an I/O device is set in binary mode, functions get_chars/2,3 and get_line/1,2 can return binaries instead of lists. The binaries are, as from Erlang/OTP R13A, encoded in UTF-8.
To work with binaries in ISO Latin-1 encoding, use the file module instead.
For conversion functions between character encodings, see the unicode module.

๐Ÿงฌ DATA TYPES ๐Ÿงฌ

Hereโ€™s the type lineup, fr fr:

device() = atom() | pid()

opt_pair() =
    {binary, boolean()} |
    {echo, boolean()} |
    {expand_fun, expand_fun()} |
    {encoding, encoding()}

expand_fun() =
    fun((term()) -> {yes | no, string(), [string(), ...]})

encoding() =
    latin1 | unicode | utf8 | utf16 | utf32 |
    {utf16, big | little} |
    {utf32, big | little}

setopt() = binary | list | opt_pair()

format() = atom() | string() | binary()

location() = erl_anno:location()

prompt() = atom() | unicode:chardata()

server_no_data() = {error, ErrorDescription :: term()} | eof
  • device() โ€” An I/O device, either standard_io, standard_error, a registered name, or a pid handling I/O protocols (returned from file:open/2). For more information about the built-in devices see Standard Input/Output and Standard Error.
  • server_no_data() โ€” What the I/O server sends when there is no data.

๐Ÿš€ EXPORTS ๐Ÿš€

๐Ÿงฎ columns

columns() -> {ok, integer() >= 1} | {error, enotsup}

columns(IoDevice) -> {ok, integer() >= 1} | {error, enotsup}

Types:

IoDevice = device()

Retrieves the number of columns of the IoDevice (that is, the width of a terminal). The function succeeds for terminal devices and returns {error, enotsup} for all other I/O devices. slay. ๐ŸŒˆ


โœ๏ธ format / fwrite

format(Format) -> ok

format(Format, Data) -> ok

format(IoDevice, Format, Data) -> ok

fwrite(Format) -> ok

fwrite(Format, Data) -> ok

fwrite(IoDevice, Format, Data) -> ok

Types:

IoDevice = device()
Format = format()
Data = [term()]

Writes the items in Data ([]) on the standard output (IoDevice) in accordance with Format. Format contains plain characters that are copied to the output device, and control sequences for formatting, see below. If Format is an atom or a binary, it is first converted to a list with the aid of atom_to_list/1 or binary_to_list/1. Example:

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

The general format of a control sequence is ~F.P.PadModC.

The character C determines the type of control sequence to be used. It is the only required field. All of F, P, Pad, and Mod are optional. For example, to use a # for Pad but use the default values for F and P, you can write ~..#C.

  • F โ€” the field width of the printed argument. A negative value means that the argument is left-justified within the field, otherwise right-justified. If no field width is specified, the required print width is used. If the field width specified is too small, the whole field is filled with * characters.
  • P โ€” 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, argument within is used to determine print width.
  • Pad โ€” 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).
  • Mod โ€” the control sequence modifier. This is one or more characters that change the interpretation of Data. The current modifiers are t, for Unicode translation, and l, for stopping p and P from detecting printable characters.

If F, P, or Pad is a * character, the next argument in Data is used as the value. For example:

1> io:fwrite("~*.*.0f~n",[9, 5, 3.14159265]).
003.14159
ok

To use a literal * character as Pad, it must be passed as an argument:

2> io:fwrite("~*.*.*f~n",[9, 5, $*, 3.14159265]).
**3.14159
ok

๐ŸŽ€ Available control sequences ๐ŸŽ€

  • ~ โ€” Character ~ is written.
  • c โ€” The argument is a number that is interpreted as an ASCII code. The precision is the number of times the character is printed and defaults to the field width, which in turn defaults to 1. Example:
1> io:fwrite("|~10.5c|~-10.5c|~5c|~n", [$a, $b, $c]).
|     aaaaa|bbbbb     |ccccc|
ok

If the Unicode translation modifier (t) is in effect, the integer argument can be any number representing a valid Unicode codepoint, otherwise it is to be an integer less than or equal to 255, otherwise it is masked with 16#FF:

2> io:fwrite("~tc~n",[1024]).
\x{400}
ok
3> io:fwrite("~c~n",[1024]).
^@
ok
  • f โ€” The argument is a float that is written as [-]ddd.ddd, where the precision is the number of digits after the decimal point. The default precision is 6 and it cannot be < 1.
  • e โ€” The argument is a float that is written as [-]d.ddde+-ddd, where the precision is the number of digits written. The default precision is 6 and it cannot be < 2.
  • g โ€” The argument is a float that is written as f, if it is >= 0.1 and < 10000.0. Otherwise, it is written in the e format. The precision is the number of significant digits. It defaults to 6 and is not to be < 2. If the absolute value of the float does not allow it to be written in the f format with the desired number of significant digits, it is also written in the e format.
  • s โ€” Prints the argument with the string syntax. The argument is, if no Unicode translation modifier is present, an iolist(), a binary(), or an atom(). If the Unicode translation modifier (t) is in effect, the argument is unicode:chardata(), meaning that binaries are in UTF-8. The characters are printed without quotes. The string is first truncated by the specified precision and then padded and justified to the specified field width. The default precision is the field width.

This format can be used for printing any object and truncating the output so it fits a specified field:

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

A list with integers > 255 is considered an error if the Unicode translation modifier is not specified:

4> io:fwrite("~ts~n",[[1024]]).
\x{400}
ok
5> io:fwrite("~s~n",[[1024]]).
** exception error: bad argument
     in function  io:format/3
        called as io:format(<0.53.0>,"~s~n",[[1024]])
  • 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. Atom characters > 255 are escaped unless the Unicode translation modifier (t) is used. Floats are printed accurately as the shortest, correctly rounded string.
  • 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. Left-justification is not supported. It also tries to detect flat lists of printable characters and output these as strings. For example:
1> T = [{attributes,[[{id,age,1.50000},{mode,explicit},
{typename,"INTEGER"}], [{id,cho},{mode,explicit},{typename,'Cho'}]]},
{typename,'Person'},{tag,{'PRIVATE',3}},{mode,implicit}].
...
2> io:fwrite("~w~n", [T]).
[{attributes,[[{id,age,1.5},{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
3> io:fwrite("~62p~n", [T]).
[{attributes,[[{id,age,1.5},
               {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 write/1 or format/1,2,3. For example, using T above:

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

okay so as of Erlang/OTP 21.0 there's a whole new vibe: if you set the field width to 0, that literally means "this line is infinitely long" โ€” like, no line breaks get inserted, ever. iconic. fr:

5> io:fwrite("~0p~n", [lists:seq(1, 30)]).
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
ok

and when you add the l modifier? no detection of printable character lists happens at all. like it just stops trying to be cute about strings. example:

6> S = [{a,"a"}, {b, "b"}], io:fwrite("~15p~n", [S]).
[{a,"a"},
 {b,"b"}]
ok
7> io:fwrite("~15lp~n", [S]).
[{a,[97]},
 {b,[98]}]
ok

see how ~15lp gave you the raw codepoints instead of pretending it's a string? that's the l doing its thing โœจ


now the Unicode translation modifier t โ€” this one tells the formatter how to treat characters that live outside the Latin-1 range of codepoints, and it applies to atoms, strings, and binaries. for example, printing an atom that contains a character > 255:

8> io:fwrite("~p~n",[list_to_atom([1024])]).
ok
9> io:fwrite("~tp~n",[list_to_atom([1024])]).
ok

๐Ÿ’… by default, Erlang only detects lists of characters in the Latin-1 range as strings โ€” but the +pc unicode flag can change that (peep printable_range/0 for the deets). example time:

10> io:fwrite("~p~n",[[214]]).
"ร–"
ok
11> io:fwrite("~p~n",[[1024]]).
[1024]
ok
12> io:fwrite("~tp~n",[[1024]]).
[1024]
ok

but if Erlang was started with +pc unicode:

13> io:fwrite("~p~n",[[1024]]).
[1024]
ok
14> io:fwrite("~tp~n",[[1024]]).
"ะ€"
ok

similar vibes for binaries โ€” ones that look like UTF-8 encoded strings get output with the binary string syntax when you specify the t modifier:

15> io:fwrite("~p~n", [<<208,128>>]).
<<208,128>>
ok
16> io:fwrite("~tp~n", [<<208,128>>]).
<<"ะ€"/utf8>>
ok
17> io:fwrite("~tp~n", [<<128,128>>]).
<<128,128>>
ok
bestie notice how that last one didn't turn into a string โ€” because it's not valid UTF-8, so the formatter is like "nope, bytes it is" ๐Ÿ’€

W

writes data in the same way as ~w, except it takes an extra argument that's the maximum depth to which terms get printed. anything below that depth gets replaced with .... for example, using T from above:

8> io:fwrite("~W~n", [T,9]).
[{attributes,[[{id,age,1.5},{mode,explicit},{typename,...}],
[{id,cho},{mode,...},{...}]]},{typename,'Person'},
{tag,{'PRIVATE',3}},{mode,implicit}]
ok
โš ๏ธ real talk: if the maximum depth is reached, the output cannot be read back in. also, that ,... form inside a tuple means "there are more elements in this tuple but they're below the print depth." so don't @ me when your round-trip breaks ๐Ÿ™ˆ

P

writes data in the same way as ~p, but (you guessed it) takes an extra argument that's the max depth. anything below that depth becomes .... like:

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

B

writes an integer in base 2-36, and the default base is 10. negatives get a leading dash. the precision field selects the base, so:

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

X

like B, but it takes an extra argument that gets inserted as a prefix before the number โ€” but after the leading dash, if there is one.

the prefix can be a possibly deep list of characters, or an atom. example:

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

#

like B, but prints the number with an Erlang style #-separated base prefix. example:

1> io:fwrite("~.10#~n", [31]).
10#31
ok
2> io:fwrite("~.16#~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. that's it. that's the whole job. humble legend ๐ŸŽ€

i

ignores the next term. yes literally just skips it. main character energy of "not my problem" ๐Ÿ’…


the function returns:

  • ok โ€” the formatting succeeded. slay ๐Ÿซถ

if an error occurs, there is no output. example:

1> 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
2> io:fwrite("~s", [65]).
** exception error: bad argument
     in function  io:format/3
        called as io:format(<0.53.0>,"~s","A")

so in that second one, the person tried to output the single character 65 using the string formatting directive "~s" โ€” and the runtime was like absolutely not ๐Ÿ˜ญ


๐ŸŒธ fread(Prompt, Format) -> Result

๐ŸŒธ fread(IoDevice, Prompt, Format) -> Result

Types

IoDevice = device()
Prompt = prompt()
Format = format()
Result =
    {ok, Terms :: [term()]} |
    {error, {fread, FreadError :: io_lib:fread_error()}} |
    server_no_data()
server_no_data() = {error, ErrorDescription :: term()} | eof

reads characters from standard input (or from IoDevice if you pass one), prompting with Prompt, and interprets what it gets according to Format. Format is full of control sequences that direct how the input gets interpreted. it's the reading counterpart to formatting โœจ

Format can contain the following:

  • whitespace characters (Space, Tab, and Newline) โ€” these cause input to be read up to the next non-whitespace character.
  • ordinary characters โ€” these must match the next input character.
  • control sequences โ€” these have the general format ~*FMC, where:
    • character * is an optional return suppression character. it gives you a way to specify a field that is to be omitted.
    • F is the field width of the input field.
    • M is an optional translation modifier (t is the only supported one, and it means Unicode translation).
    • C determines the type of control sequence.

unless otherwise specified, leading whitespace is ignored for all control sequences. and heads up: an input field cannot be more than one line wide.

available control sequences:

  • ~ โ€” 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 the base. leading whitespace characters are not skipped.
  • - โ€” an optional sign character is expected. a sign character - gives return value -1. sign character + or no sign at all gives 1. the field width parameter is ignored. leading whitespace 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-whitespace characters is read. if a field width has been specified, that number of characters is read and all trailing whitespace characters are stripped. an Erlang string (list of characters) is returned.

if Unicode translation is in effect (~ts), characters > 255 are accepted, otherwise they're not. with the translation modifier, the returned list can as a consequence also contain integers > 255:

1> io:fread("Prompt> ","~s").
Prompt> <Characters beyond latin1 range not printable in this medium>
{error,{fread,string}}
2> io:fread("Prompt> ","~ts").
Prompt> <Characters beyond latin1 range not printable in this medium>
{ok,[[1091,1085,1080,1094,1086,1076,1077]]}
  • a โ€” similar to s, but the resulting string gets converted into an atom.
  • c โ€” the number of characters equal to the field width get read (default is 1) and returned as an Erlang string. but unlike s, leading and trailing whitespace characters are not omitted. all characters are returned.

the Unicode translation modifier works the same as with s:

1> io:fread("Prompt> ","~c").
Prompt> <Character beyond latin1 range not printable in this medium>
{error,{fread,string}}
2> io:fread("Prompt> ","~tc").
Prompt> <Character beyond latin1 range not printable in this medium>
{ok,[[1091]]}
  • l โ€” returns the number of characters that have been scanned up to that point, including whitespace characters.

the function returns:

  • {ok, Terms} โ€” the read was successful, and Terms is the list of successfully matched and read items. ๐ŸŽ‰
  • eof โ€” end of file was encountered.
  • {error, FreadError} โ€” the reading failed, and FreadError gives you a hint about what went wrong. ๐Ÿ˜ญ
  • {error, ErrorDescription} โ€” the read flopped ๐Ÿ˜ญ and ErrorDescription is there to give you a hint about why.

Examples, bestie โ€” run these and watch ๐Ÿ’…

20> io:fread('enter>', "~f~f~f").
enter>1.9 35.5e3 15.0
{ok,[1.9,3.55e4,15.0]}
21> io:fread('enter>', "~10f~d").
enter>     5.67899
{ok,[5.678,99]}
22> io:fread('enter>', ":~10s:~10c:").
enter>:   alan   :   joe    :
{ok, ["alan", "   joe    "]}

โœจ get_chars(Prompt) -> Data | server_no_data() โœจ

๐ŸŒธ get_chars(IoDevice, Prompt, Count) -> Data | server_no_data() ๐ŸŒธ

Types, so you know what you're feeding it ๐Ÿฅบ

IoDevice = device()
Prompt = prompt()
Count = integer() >= 0
Data = string() | unicode:unicode_binary()
server_no_data() = {error, ErrorDescription :: term()} | eof

So this one grabs Count characters from standard input (or from IoDevice if you passed one) and it prompts you with Prompt first, like a polite little function ๐Ÿซถ

What you get back:

  • Data โ€” the actual input characters โœจ. Heads up though: if the I/O device supports Unicode, the data can represent codepoints > 255 (that's the latin1 range, iykyk). And if the I/O server is set to deliver binaries, they come encoded in UTF-8 (regardless of whether the I/O device supports Unicode โ€” yeah, it's giving "don't ask", but that's the rule ๐Ÿ’€).
  • eof โ€” hit end of file, that's all she wrote ๐ŸŽ€
  • {error, ErrorDescription} โ€” some other (rare) error condition, like {error, estale} if you're reading from an NFS file system. Rare but real ๐Ÿ™ˆ

๐Ÿฆ‹ get_line(Prompt) -> Data | server_no_data() ๐Ÿฆ‹

๐Ÿฆ‹ get_line(IoDevice, Prompt) -> Data | server_no_data() ๐Ÿฆ‹

Types:

IoDevice = device()
Prompt = prompt()
Data = string() | unicode:unicode_binary()
server_no_data() = {error, ErrorDescription :: term()} | eof

Reads a line from standard input (or IoDevice), prompting with Prompt. It's literally get_chars's chill older sister ๐Ÿ’œ

Returns:

  • Data โ€” the characters in the line, terminated by a line feed (or end of file, whichever hits first). If the I/O device supports Unicode, the data can represent codepoints > 255 (the latin1 range). If the I/O server is set to deliver binaries, they're encoded in UTF-8 (regardless of if the I/O device supports Unicode) โœจ
  • eof โ€” end of file was encountered ๐ŸŒˆ
  • {error, ErrorDescription} โ€” other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ˜ญ

๐Ÿ’… getopts() -> [opt_pair()] | {error, Reason} ๐Ÿ’…

๐Ÿ’… getopts(IoDevice) -> [opt_pair()] | {error, Reason} ๐Ÿ’…

Types:

IoDevice = device()
Reason = term()

This one's the vibe check for your I/O device ๐Ÿ‘‘ โ€” it asks for all available options and their current values for a specific I/O device. Like so:

1> {ok,F} = file:open("/dev/null",[read]).
{ok,<0.42.0>}
2> io:getopts(F).
[{binary,false},{encoding,latin1}]

Here the file I/O server hands back all available options for a file, which are the expected ones: encoding and binary. But the standard shell is extra ๐Ÿ’… โ€” it's got some more options:

3> io:getopts().
[{expand_fun,#Fun<group.0.120017273>},
 {echo,true},
 {binary,false},
 {encoding,unicode}]

And yeah, as you can see, this example is run in an environment where the terminal supports Unicode input and output ๐ŸŒโœจ


๐ŸŽ€ nl() -> ok ๐ŸŽ€

๐ŸŽ€ nl(IoDevice) -> ok ๐ŸŽ€

Types:

IoDevice = device()

Writes a new line to standard output (or IoDevice). That's it. That's the whole function. Tiny but iconic ๐Ÿ’–


โญ parse_erl_exprs(Prompt) -> Result โญ

โญ parse_erl_exprs(IoDevice, Prompt) -> Result โญ

โญ parse_erl_exprs(IoDevice, Prompt, StartLocation) -> Result โญ

โญ parse_erl_exprs(IoDevice, Prompt, StartLocation, Options) -> Result โญ

Types, buckle up ๐Ÿซถ

IoDevice = device()
Prompt = prompt()
StartLocation = location()
Options = erl_scan:options()
Result = parse_ret()
parse_ret() =
    {ok,
     ExprList :: [erl_parse:abstract_expr()],
     EndLocation :: location()} |
    {eof, EndLocation :: location()} |
    {error,
     ErrorInfo :: erl_scan:error_info() | erl_parse:error_info(),
     ErrorLocation :: location()} |
    server_no_data()
server_no_data() = {error, ErrorDescription :: term()} | eof

Okay so this reads data from standard input (or IoDevice), prompting with Prompt. Reading starts at location StartLocation (default is 1). The Options argument gets passed on as the Options argument of erl_scan:tokens/4 โ€” no cap, it's just forwarded ๐Ÿฆ‹

Then the data is tokenized and parsed as if it was a sequence of Erlang expressions until a final dot (.) is reached. Main character parsing energy ๐Ÿ‘‘

What comes back:

  • {ok, ExprList, EndLocation} โ€” parsing was successful, slay โœจ
  • {eof, EndLocation} โ€” end of file was encountered by the tokenizer
  • eof โ€” end of file was encountered by the I/O server (yes, these are different, don't @ me ๐Ÿ’€)
  • {error, ErrorInfo, ErrorLocation} โ€” an error happened while tokenizing or parsing ๐Ÿ˜ญ
  • {error, ErrorDescription} โ€” other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ™ˆ

Example time ๐Ÿ“

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

(Yeah that second one has a space before the paren in the original. We keep it. Character for character, bestie ๐Ÿซถ)


๐ŸŒˆ parse_erl_form(Prompt) -> Result ๐ŸŒˆ

๐ŸŒˆ parse_erl_form(IoDevice, Prompt) -> Result ๐ŸŒˆ

๐ŸŒˆ parse_erl_form(IoDevice, Prompt, StartLocation) -> Result ๐ŸŒˆ

๐ŸŒˆ parse_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result ๐ŸŒˆ

Types:

IoDevice = device()
Prompt = prompt()
StartLocation = location()
Options = erl_scan:options()
Result = parse_form_ret()
parse_form_ret() =
    {ok,
     AbsForm :: erl_parse:abstract_form(),
     EndLocation :: location()} |
    {eof, EndLocation :: location()} |
    {error,
     ErrorInfo :: erl_scan:error_info() | erl_parse:error_info(),
     ErrorLocation :: location()} |
    server_no_data()
server_no_data() = {error, ErrorDescription :: term()} | eof

Basically the same routine as parse_erl_exprs but for forms instead of expressions ๐Ÿ‘‘ Reads data from standard input (or IoDevice), prompts with Prompt, starts at location StartLocation (default 1), and Options is passed on as the Options argument of erl_scan:tokens/4 ๐Ÿ’…

The twist: the data is tokenized and parsed as if it was an Erlang form โ€” that's one of the valid Erlang expressions in an Erlang source file โ€” until a final dot (.) is reached. Same energy, different wrapper ๐ŸŽ€

Returns:

  • {ok, AbsForm, EndLocation} โ€” parsing was successful โœจ
  • {eof, EndLocation} โ€” end of file was encountered by the tokenizer
  • eof โ€” end of file was encountered by the I/O server
  • {error, ErrorInfo, ErrorLocation} โ€” error occurred while tokenizing or parsing ๐Ÿ˜ญ
  • {error, ErrorDescription} โ€” other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ™ˆ

๐Ÿงš printable_range() -> unicode | latin1 ๐Ÿงš

Returns the user-requested range of printable Unicode characters โœจ

So, the user can request a range of characters that are to be considered printable when the shell and the formatting functions heuristically detect strings. How? By supplying +pc <range> when starting Erlang. Literally that simple ๐Ÿ’…

The only valid values for <range> are latin1 and unicode:

  • latin1 โ€” means only code points < 256 (except control characters, and so on) are considered printable ๐ŸŽ€
  • unicode โ€” means all printable characters in all Unicode character ranges are considered printable by the I/O functions ๐ŸŒ

By default, Erlang is started so that only the latin1 range of characters indicate that a list of integers is a string. So that's the default vibe ๐Ÿ‘‘

The simplest way to use the setting is to call io_lib:printable_list/1, which uses the return value of this function to decide if a list is a string of printable characters. Iconic teamwork ๐Ÿซถ

Note: In a future release, this function may return more values and ranges. To avoid compatibility problems, it is recommended to use function io_lib:printable_list/1. โ€” like, forward-compatibility is self-care, bestie ๐Ÿ’–

๐Ÿ’– put_chars(CharData) -> ok ๐Ÿ’–

๐Ÿ’– put_chars(IoDevice, CharData) -> ok ๐Ÿ’–

Types:

IoDevice = device()
CharData = unicode:chardata()

Writes the characters of CharData to the I/O server (IoDevice). Simple, effective, ate ๐Ÿ’…


๐Ÿ”ฅ read(Prompt) -> Result ๐Ÿ”ฅ

๐Ÿ”ฅ read(IoDevice, Prompt) -> Result ๐Ÿ”ฅ

Types:

IoDevice = device()
Prompt = prompt()
Result =
    {ok, Term :: term()} | server_no_data() | {error,
ErrorInfo}
ErrorInfo = erl_scan:error_info() | erl_parse:error_info()
server_no_data() = {error, ErrorDescription :: term()} | eof

Reads a term Term from standard input (or IoDevice), prompting with Prompt. Yeah, actual terms โ€” this is the main character of reading ๐Ÿ‘‘

What it gives back:

  • {ok, Term} โ€” parsing was successful, we love to see it โœจ
  • eof โ€” end of file was encountered ๐ŸŽ€
  • {error, ErrorInfo} โ€” the parsing failed ๐Ÿ˜ญ
  • {error, ErrorDescription} โ€” other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ™ˆ

๐Ÿฆ‹ read(IoDevice, Prompt, StartLocation) -> Result ๐Ÿฆ‹

๐Ÿฆ‹ read(IoDevice, Prompt, StartLocation, Options) -> Result ๐Ÿฆ‹

Types:

IoDevice = device()
Prompt = prompt()
StartLocation = location()
Options = erl_scan:options()
Result =
    {ok, Term :: term(), EndLocation :: location()} |
    {eof, EndLocation :: location()} |
    server_no_data() |
    {error, ErrorInfo, ErrorLocation :: location()}
ErrorInfo = erl_scan:error_info() | erl_parse:error_info()
server_no_data() = {error, ErrorDescription :: term()} | eof

Reads a term Term from IoDevice, prompting with Prompt. Reading starts at location StartLocation, and the Options argument gets passed on as the Options argument of function erl_scan:tokens/4 ๐ŸŒธ

Returns:

  • {ok, Term, EndLocation} โ€” slay, it parsed successfully ๐Ÿ’…
  • {eof, EndLocation} โ€” end of file was encountered, bestie ๐Ÿซถ
  • {error, ErrorInfo, ErrorLocation} โ€” the parsing failed ๐Ÿ˜ญ
  • {error, ErrorDescription} โ€” other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ’€

rows() / rows(IoDevice) โ€” how tall is your terminal, bestie ๐Ÿ“

rows() -> {ok, integer() >= 1} | {error, enotsup}

rows(IoDevice) -> {ok, integer() >= 1} | {error, enotsup}

Types:

  • IoDevice = device()

Retrieves the number of rows of IoDevice โ€” that is, the height of a terminal ๐Ÿ‘‘. The function only succeeds for terminal devices; for all other I/O devices the function returns {error, enotsup} ๐Ÿ™ˆ.


scan_erl_exprs(...) โ€” tokenize Erlang expressions like a main character ๐Ÿ”ฅ

scan_erl_exprs(Prompt) -> Result

scan_erl_exprs(Device, Prompt) -> Result

scan_erl_exprs(Device, Prompt, StartLocation) -> Result

scan_erl_exprs(Device, Prompt, StartLocation, Options) -> Result

Types:

  • Device = device()
  • Prompt = prompt()
  • StartLocation = location()
  • Options = erl_scan:options()
  • Result = erl_scan:tokens_result() | server_no_data()
  • server_no_data() = {error, ErrorDescription :: term()} | eof

Reads data from the standard input (IoDevice), prompting it with Prompt ๐Ÿ’Œ. Reading starts at location StartLocation (1). Argument Options is passed on as argument Options of function erl_scan:tokens/4. The data is tokenized as if it were a sequence of Erlang expressions until a final dot (.) is reached. This token is also returned โญ.

The function returns:

  • {ok, Tokens, EndLocation}: the tokenization succeeded ๐ŸŽ€
  • {eof, EndLocation}: end of file was encountered by the tokenizer ๐Ÿฆ‹
  • eof: end of file was encountered by the I/O server ๐ŸŒธ
  • {error, ErrorInfo, ErrorLocation}: an error occurred while tokenizing ๐Ÿ˜ญ
  • {error, ErrorDescription}: other (rare) error condition, such as {error, estale} if reading from an NFS file system ๐Ÿ’€

Example:

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

scan_erl_form(...) โ€” same energy, but for one whole Erlang form ๐Ÿฆ‹

scan_erl_form(Prompt) -> Result

scan_erl_form(IoDevice, Prompt) -> Result

scan_erl_form(IoDevice, Prompt, StartLocation) -> Result

scan_erl_form(IoDevice, Prompt, StartLocation, Options) -> Result

Types:

  • IoDevice = device()
  • Prompt = prompt()
  • StartLocation = location()
  • Options = erl_scan:options()
  • Result = erl_scan:tokens_result() | server_no_data()
  • server_no_data() = {error, ErrorDescription :: term()} | eof

Reads data from the standard input (IoDevice), prompting it with Prompt ๐Ÿ’–. Starts reading at location StartLocation (1). Argument Options is passed on as argument Options of function erl_scan:tokens/4. The data is tokenized as if it was an Erlang form โ€” one of the valid Erlang expressions in an Erlang source file โ€” until a final dot (.) is reached. This last token is also returned โœจ.

The return values are the same as for scan_erl_exprs/1,2,3,4 ๐Ÿซถ.


setopts(...) โ€” tune your I/O deviceโ€™s vibe ๐ŸŽ›๏ธ

setopts(Opts) -> ok | {error, Reason}

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

Types:

  • IoDevice = device()
  • Opts = [setopt()]
  • Reason = term()

Set options for the standard I/O device (IoDevice) ๐Ÿ’….

Possible options and values vary depending on the I/O device. For a list of supported options and their current values on a specific I/O device, use function getopts/1 ๐Ÿ”.

The options and values supported by the OTP I/O devices are as follows:

  • binary, list, or {binary, boolean()} โ€” If set in binary mode (binary or {binary, true}), the I/O server sends binary data (encoded in UTF-8) as answers to the get_line, get_chars, and, if possible, get_until requests (for details, see section The Erlang I/O Protocol in the User's Guide). The immediate effect is that get_chars/2,3 and get_line/1,2 return UTF-8 binaries instead of lists of characters for the affected I/O device ๐ŸŒˆ.

By default, all I/O devices in OTP are set in list mode. However, the I/O functions can handle any of these modes and so should other, user-written, modules behaving as clients to I/O servers ๐Ÿ‘‘.

This option is supported by the standard shell (group.erl), the 'oldshell' (user.erl), and the file I/O servers โญ.

  • {echo, boolean()} โ€” Denotes if the terminal is to echo input. Only supported for the standard shell I/O server (group.erl) ๐ŸŽ€.
  • {expand_fun, expand_fun()} โ€” Provides a function for tab-completion (expansion) like the Erlang shell. This function is called when the user presses the Tab key. The expansion is active when calling line-reading functions, such as get_line/1,2 ๐Ÿฆ‹.

The function is called with the current line, up to the cursor, as a reversed string. It is to return a three-tuple: {yes|no, string(), [string(), ...]}. The first element gives a beep if no, otherwise the expansion is silent; the second is a string that will be entered at the cursor position; the third is a list of possible expansions. If this list is not empty, it is printed and the current input line is written once again โœจ.

Trivial example (beep on anything except empty line, which is expanded to "quit"):

fun("") -> {yes, "quit", []};
   (_) -> {no, "", ["quit"]} end

This option is only supported by the standard shell (group.erl) ๐Ÿ’–.

  • {encoding, latin1 | unicode} โ€” Specifies how characters are input or output from or to the I/O device, implying that, for example, a terminal is set to handle Unicode input and output or a file is set to handle UTF-8 data encoding ๐ŸŒธ.

The option does not affect how data is returned from the I/O functions or how it is sent in the I/O protocol, it only affects how the I/O device is to handle Unicode characters to the "physical" device ๐Ÿ‘€.

The standard shell is set for unicode or latin1 encoding when the system is started. The encoding is set with the help of the LANG or LC_CTYPE environment variables on Unix-like system or by other means on other systems. So, the user can input Unicode characters and the I/O device is in {encoding, unicode} mode if the I/O device supports it. The mode can be changed, if the assumption of the runtime system is wrong, by setting this option ๐Ÿซถ.

The I/O device used when Erlang is started with the "-oldshell" or "-noshell" flags is by default set to latin1 encoding, meaning that any characters > codepoint 255 are escaped and that input is expected to be plain 8-bit ISO Latin-1. If the encoding is changed to Unicode, input and output from the standard file descriptors are in UTF-8 (regardless of operating system) ๐Ÿ”ฅ.

Files can also be set in {encoding, unicode}, meaning that data is written and read as UTF-8. More encodings are possible for files, see below ๐Ÿ’œ.

{encoding, unicode | latin1} is supported by both the standard shell (group.erl including werl on Windows), the 'oldshell' (user.erl), and the file I/O servers ๐Ÿ’….

  • {encoding, utf8 | utf16 | utf32 | {utf16,big} | {utf16,little} | {utf32,big} | {utf32,little}} โ€” For disk files, the encoding can be set to various UTF variants. This has the effect that data is expected to be read as the specified encoding from the file, and the data is written in the specified encoding to the disk file ๐ŸŒˆ.

{encoding, utf8} has the same effect as {encoding, unicode} on files โญ.

The extended encodings are only supported on disk files (opened by function file:open/2) ๐ŸŽ€.


write(...) โ€” just put the term out there ๐Ÿ’Œ

write(Term) -> ok

write(IoDevice, Term) -> ok

Types:

  • IoDevice = device()
  • Term = term()

Writes term Term to the standard output (IoDevice) โœจ.


๐Ÿ’– STANDARD INPUT/OUTPUT ๐Ÿ’–

All Erlang processes have a default standard I/O device ๐Ÿ‘‘. This device is used when no IoDevice argument is specified in the function calls in this module. However, it is sometimes desirable to use an explicit IoDevice argument that refers to the default I/O device. This is the case with functions that can access either a file or the default I/O device. The atom standard_io has this special meaning ๐Ÿซถ. The following example illustrates this:

27> io:read('enter>').
enter>foo.
{ok,foo}
28> io:read(standard_io, 'enter>').
enter>bar.
{ok,bar}

standard_io is an alias for group_leader/0, so in order to change where the default input/output requests are sent you can change the group leader for the current process using group_leader(NewGroupLeader, self()) ๐Ÿ’….

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


๐Ÿšจ STANDARD ERROR ๐Ÿšจ

In certain situations, especially when the standard output is redirected, access to an I/O server specific for error messages can be convenient ๐Ÿ˜ญ. The I/O device standard_error can be used to direct output to whatever the current operating system considers a suitable I/O device for error output. Example on a Unix-like operating system:

$ erl -noshell -noinput -eval 'io:format(standard_error,"Error: ~s~n",["error 11"]),'\
'init:stop().' > /dev/null
Error: error 11

๐Ÿง ERROR INFORMATION ๐Ÿง

The ErrorInfo mentioned in this module is the standard ErrorInfo structure that is returned from all I/O modules. It has the following format:

{ErrorLocation, Module, ErrorDescriptor}

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

Module:format_error(ErrorDescriptor)

and thatโ€™s the whole page, bestie ๐ŸŽ€ โ€” source: Ericsson AB ยท version: stdlib 4.3.1.3 ยท page: io(3erl) ยท date: not in the footer ๐Ÿซถ๐Ÿ’–

๐Ÿ“ฆ where this page comes from