2011-02-05 43 views
6

例如,我有10个字符串文本的txt文件。我怎样才能用erlang读取这段文字的前5个字符串?Erlang从文件中读取前5行

谢谢。

+0

@OP :你被要求接受一个答案,如果任何答案发布回答你的问题,并且你满意无线它。 – Arunmu 2011-02-05 08:12:17

+0

@ArunMu:即使在昵称前没有“@”,用户也会看到该评论,并添加到他(她)的帖子中。 ;-) – 2011-02-05 08:43:58

回答

8

可能是你想要的file:open/2file:read_line/1组合具有缓冲功能。

韵:

$ cat mary_lamb.txt 
Mary had a little lamb, 
little lamb, little lamb, 
Mary had a little lamb, 
whose fleece was white as snow. 
And everywhere that Mary went, 
Mary went, Mary went, 
and everywhere that Mary went, 
the lamb was sure to go. 

源文件:

$ cat ./read_n_lines.erl 
-module(read_n_lines). 
-export([read_n_lines/2]). 

read_n_lines(Filename,NumLines) -> 
    {ok, FileDev} = file:open(Filename, 
      [raw, read, read_ahead]), 
    Lines = do_read([],FileDev, NumLines), 
    file:close(FileDev), 
    Lines. 

do_read(Lines, _, 0) -> 
    lists:reverse(Lines); 
do_read(Lines, FileDev, L) -> 
    case file:read_line(FileDev) of 
      {ok, Line} -> 
       do_read([Line|Lines], FileDev, L - 1); 
      eof -> 
       do_read(Lines, FileDev, 0) 
    end. 

raw,在Modes,传递给file:open/2,允许一个文件更快的访问,因为不需要Erlang进程来处理文件。

采样运行:

$ erl 
1> c(read_n_lines). 
{ok,read_n_lines} 
2> Lines = read_n_lines:read_n_lines("./mary_lamb.txt", 5). 
["Mary had a little lamb,\n","little lamb, little lamb,\n", 
"Mary had a little lamb,\n", 
"whose fleece was white as snow.\n", 
"And everywhere that Mary went,\n"] 
3> length(Lines). 
5 
4> read_n_lines:read_n_lines("./mary_lamb.txt", 666). 
["Mary had a little lamb,\n","little lamb, little lamb,\n", 
"Mary had a little lamb,\n", 
"whose fleece was white as snow.\n", 
"And everywhere that Mary went,\n", 
"Mary went, Mary went,\n", 
"and everywhere that Mary went,\n", 
"the lamb was sure to go."] 
5> 

从字符串中删除换行符,您可以使用string:strip/1,2,3

5> lists:map(fun(X) -> string:strip(X, right, $\n) end, Lines). 
["Mary had a little lamb,","little lamb, little lamb,", 
"Mary had a little lamb,", 
"whose fleece was white as snow.", 
"And everywhere that Mary went,"] 
6> 
1

使用erlang的io模块。

io:read(FD,'')。

其中FD是文件句柄。

也请查找erlang文档的正确语法。

这里是一个粗略的代码

 
func(FD) -> 
case io:get_line(FD,'') of 
{ok,text}-> 
%%do something, 
func(FD); 
eof -> 
%%exit; 
error-> 
%%quit 
end 

您可以使用一个计数器,如果你想处理短短10行

2

另一种解决方案,n_times可以用在别处:

-module(n_times). 

-export([test/0]). 

test() -> 
    io:format("~p~n", [n_lines("n_times.erl", 5)]). 

n_lines(FileName, N) -> 
    {ok, FileDev} = file:open(FileName, [raw, read, read_ahead]), 
    try 
    n_times(fun() -> {ok, L} = file:read_line(FileDev), L end, N) 
    after 
    file:close(FileDev) 
    end. 

n_times(F, N) -> 
    n_times(F, N, []). 

n_times(_, 0, A) -> 
    lists:reverse(A); 
n_times(F, N, A) -> 
    n_times(F, N-1, [F()|A]).