reading and writing text file

Wiger Ulf <>
Sun Aug 3 14:45:42 CEST 2003


From: "Jilani Khaldi" <>

> > 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
"Hello"
> 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\""
ok
3> io:format("~s~n", [String]).
Say "Hello"
ok
4> length(String).
11
5>

> > 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 http://www.erlang.org/.

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).
{ok,<0.36.0>}
7> io:get_line(FileDescr, '').
"Erlang/OTP                                               October 15,
2002\n"
8> io:get_line(FileDescr, '').
"\n"
9> io:get_line(FileDescr, '').
"\n"
10> io:get_line(FileDescr, '').
"LAST MINUTE INFORMATION -- Release of Erlang 5.2/OTP R9B\n"
11> file:close(FileDescr).
ok


> 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
descriptor,
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.


/Uffe




More information about the erlang-questions mailing list