reading and writing text file

Wiger Ulf ulf.wiger@REDACTED
Sun Aug 3 14:45:42 CEST 2003

From: "Jilani Khaldi" <jilani.khaldi@REDACTED>

> > You can either use file:read_file() and binary_to_list(), followed by
> > string:tokens(List, "\n") -- which will give you a list of strings, one
> > for each line of text in the file --
> It works but I still get "\" added for all quoted text. For example
> becomes \"hello\". How can I get rid of these "\".

The quoting is a matter of output formatting. The backslashes are
not really there, but added by the formatting function of the shell.
Using io:format(), ~p (pretty-print) will escape all quotes in that
fashion, whereas ~s (format as string) will not.

Erlang (BEAM) emulator version 5.2 [threads:0]

Eshell V5.2  (abort with ^G)
1> String = "Say \"Hello\"".
"Say \"Hello\""
2> io:format("~p~n", [String]).
"Say \"Hello\""
3> io:format("~s~n", [String]).
Say "Hello"
4> length(String).

> > or use io:get_line(FileDescr,'') to read one
> > line at a time from the file.
> What FileDesc means in this case and what do I have to put inside ''? I
> just have a file "a.txt" to read and see it as a list of strings.

I was perhaps a bit too terse. Apologies. I wanted to leave some
room for personal exploration. (-:

You can always look up the documentation for functions using
"erl -man <module name>", e.g. "erl -man io". Another method is to
browse the on-line documentation on

FileDescr (or IoDevice, as it is called in the io reference manual)
is a file descriptor identifying an open file.

6> {ok,FileDescr} = file:open("README", read).
7> io:get_line(FileDescr, '').
"Erlang/OTP                                               October 15,
8> io:get_line(FileDescr, '').
9> io:get_line(FileDescr, '').
10> io:get_line(FileDescr, '').
"LAST MINUTE INFORMATION -- Release of Erlang 5.2/OTP R9B\n"
11> file:close(FileDescr).

> How to append the string "Hello Erlang" to the text file "a.txt"? I can't
> find the append command.

Using {ok,OutFd} = file:open("a.txt", write) will give you a file
and clear the file a.txt, preparing it for writing.

You can then use e.g. io:format(OutFd, Format, Args), which
will behave just like io:format/2, but send the output to the file
instead of stdout.


More information about the erlang-questions mailing list