Reputation: 305
I am trying to read an integer value from a simple text file. Row in my input file looks like this:
1 4 15 43
2 4 12 33
... (many rows of 4 integers)
I have opened the file in the following way:
{ok, IoDev} = file:open("blah.txt",[read])
But only thing that I manage to read are bytes with all the functions available.
What I finally want to get from file are tuples of integers.
{1 4 15 43}
{2 4 12 33}
...
Upvotes: 3
Views: 1625
Reputation: 1030
Haven't seen edited part
/*
You can try fread/3
read() ->
{ok, IoDev} = file:open("x", [read]),
read([], IoDev).
read(List, IoDev) ->
case io:fread(IoDev, "", "~d~d~d~d") of
{ok, [A,B,C,D]} ->
read([{A,B,C,D} | List], IoDev);
eof ->
lists:reverse(List);
{error, What} ->
failed
end.
*/
Upvotes: 2
Reputation: 7654
You must first use file:read_line/1
to read a line of text, and use re:split/2
to get a list of strings containing numbers. Then use the list_to_integer
BIF to get integers.
Here's an example (surely there is a better solution):
#!/usr/bin/env escript
%% -*- erlang -*-
main([Filename]) ->
{ok, Device} = file:open(Filename, [read]),
read_integers(Device).
read_integers(Device) ->
case file:read_line(Device) of
eof ->
ok;
{ok, Line} ->
% Strip the trailing \n (ASCII 10)
StrNumbers = re:split(string:strip(Line, right, 10), "\s+", [notempty]),
[N1, N2, N3, N4] = lists:map(fun erlang:list_to_integer/1,
lists:map(fun erlang:binary_to_list/1,
StrNumbers)),
io:format("~w~n", [{N1, N2, N3, N4}]),
read_integers(Device)
end.
(EDIT)
I found a somewhat simpler solution that uses io:fread
to read formatted input. It works well in your case but fails badly when the file is badly constructed.
#!/usr/bin/env escript
%% -*- erlang -*-
main([Filename]) ->
{ok, Device} = file:open(Filename, [read]),
io:format("~w~n", [read_integers(Device)]).
read_integers(Device) ->
read_integers(Device, []).
read_integers(Device, Acc) ->
case io:fread(Device, [], "~d~d~d~d") of
eof ->
lists:reverse(Acc);
{ok, [D1, D2, D3, D4]} ->
read_integers(Device, [{D1, D2, D3, D4} | Acc]);
{error, What} ->
io:format("io:fread error: ~w~n", [What]),
read_integers(Device, Acc)
end.
Upvotes: 3