-module(test).
-export([run/1]).
open_file(FileName, Mode) ->
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
close_file(Device) ->
ok = file:close(Device).
read(File) ->
case file:read_line(File) of
{ok, Data} -> [Data | read(File)];
eof -> []
end.
run(InputFileName) ->
Device = open_file(InputFileName, read),
Data = read(Device),
[First |TheRest] = Data,
io:format("First line is ~p ~n", [First]),
close_file(Device).
原始文件
d1 and is program program the
d2 a apply copyleft free free freedom
d3 copyleft copyleft share share users
d4 released software works
d5 licenses licenses licenses licenses licenses software
d8 apply
不知何故变成了
50> test:run("input.txt").
First line is <<"d1\tand\tis\tprogram\tprogram\tthe\n">>
ok
这是表示列表的一种特殊方式吗?还是我需要使用某种模块将读取的内容转换为列表?
我的最终目标是用列表创建密钥对:
{d1 [and is program program the]}
谢谢!
从文件中读取的数据表示为二进制而不是字符串,因为binary
在打开文件时要指定模式:
{ok, Device} = file:open(FileName, [Mode, binary]), Device.
如果将其更改为:
{ok, Device} = file:open(FileName, [Mode]), Device.
您的结果将变为:
第一行是“ d1,并且是程序程序的\ n”
要获得最终结果,请将read/1
函数更改为此:
read(File) ->
case file:read_line(File) of
{ok, Data} ->
[First|Rest] = string:tokens(Data, " \t\n"),
[{First,string:join(Rest, "\t")} | read(File)];
eof -> []
end.
进行此更改后,您的程序将打印:
第一行是{“ d1”,“和\ tis \ tprogram \ tprogram \ tthe”}
其中第二个元素是一个字符串,其中的令牌与原始数据一样以制表符分隔。如果您希望第一个元素"d1"
成为原子d1
(我不能肯定从您的问题中确定这是否是您想要的),则可以使用进行转换list_to_atom/1
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句