Erlang文件差异

时间:2013-12-24 07:50:58

标签: file erlang diff

我需要获得2个文件的差异。例如:

File 1:
asd
qwe

File 2:
asd
qwe
zxc

我的代码中需要行zxc。如何用erlang做到?

2 个答案:

答案 0 :(得分:1)

我将以这种方式解决问题:

-module(main).

-export([main/0]).    

read_all(F) ->
    R = file:read_line(F),
    read_all(F, R, []).
read_all(F, {ok, Data}, A) ->
    R = file:read_line(F), 
    read_all(F, R, A ++ [Data]);
read_all(_, eof, A) ->
    A.

main() ->
    {ok, F1} = file:open("file1", [raw, read_ahead]),
    F1Data = read_all(F1),
    {ok, F2} = file:open("file2", [raw, read_ahead]),
    F2Data = read_all(F2),   
    S1 = sets:from_list(F1Data),
    S2 = sets:from_list(F2Data),
    io:format("~p ~p~n", [S1, S2]),
    sets:subtract(S2, S1).

您可能需要通过以更易于阅读的格式显示设置操作的结果(本例中为sets:subtract)来对其进行润色。

答案 1 :(得分:1)

这个怎么样?

1> {ok,Bin}=file:read_file("1.txt").
{ok,<<"asd\nqwe\n">>}
2> {ok,Bin2}=file:read_file("2.txt").
{ok,<<"asd\nqwe\nzxc\n">>}
3> L1=binary:split(Bin, <<"\n">>, [global]).   
[<<"asd">>,<<"qwe">>,<<>>]
4> L2=binary:split(Bin2, <<"\n">>, [global]).
[<<"asd">>,<<"qwe">>,<<"zxc">>,<<>>]
5> L2 -- L1.    
[<<"zxc">>]

但是如果你想要第一个文件中的其他区别,你也必须做L1 - L2。