Erlang逐行比较两个二进制文件

时间:2017-04-13 23:57:46

标签: erlang

我试图比较两个二进制文件的差异,但是在阅读文件时逐行比较会感到困惑。就像读取两个文件中的第一行一样,然后进行比较,然后读取两个文件的第二行进行比较

read(B1,B2) ->
    {ok, Binary} = file:read_file(B1),
    X=[binary_to_list(Bin)||Bin<-binary:split(Binary, [<<"\n">>], [global])],
    {ok, Data} = file:read_file(B2),
    Y=[binary_to_list(Bin)||Bin<-binary:split(Data, [<<"\n">>], [global])],
    compare(X,Y).

compare(X,Y)->
    C3=lists:subtract(F1, F2),
    io:format("~p~p",[C3,length(C3)]).

2 个答案:

答案 0 :(得分:0)

你可以使用list:zip()将两个列表连接成一个{Xn, Yn}对的列表(检查它们的长度是否相同),然后在结果上列出:foreach()。

答案 1 :(得分:0)

您应该提供有关您想要做什么以及到目前为止尝试过的内容的更多详细信息。

我加入了一个执行比较的代码示例,使用行号打印不同的行,如果一个文件更长,则打印剩余的行。

我不会将二进制文件转换为列表,这是不必要且效率低下的。

-module (comp).

-export ([compare/2]).

compare(F1,F2) ->
    {ok,B1} = file:read_file(F1),
    {ok,B2} = file:read_file(F2),
    io:format("compare file 1: ~s to file 2 ~s~n",[F1,F2]),
    compare( binary:split(B1, [<<"\n">>], [global]),
             binary:split(B2, [<<"\n">>], [global]),
             1).

compare([],[],_) ->
    io:format("the 2 files have the same length~n"),
    done();
compare([],L,N) ->
    io:format("----> file 2 is longer:\n"),
    print(L,N);
compare(L,[],N) ->
    io:format("----> file 1 is longer:\n"),
    print(L,N);
compare([X|T1],[X|T2],N) -> compare(T1,T2,N+1);
compare([X1|T1],[X2|T2],N) ->
    io:format("at line ~p,~nfile 1 is: ~s~nfile 2 is: ~s~n",[N,X1,X2]),
    compare(T1,T2,N+1).

print([],_) -> done();
print([X|T],N) ->
    io:format("line ~p: ~s~n",[N,X]),
    print(T,N+1).

done() -> io:format("end of comparison~n").

小测试:

1> c(comp).                                                  
{ok,comp}
2> comp:compare("../doc/sample.txt","../doc/sample_mod.txt").
compare file 1: ../doc/sample.txt to file 2 ../doc/sample_mod.txt
at line 9,
file 1 is: Here's an example:
file 2 is: Here's an example (modified):
at line 22,
file 1 is: ```
file 2 is: ```
----> file 2 is longer:
line 23: 
line 24: Extra text...
line 25: 
end of comparison
ok
3> comp:compare("../doc/sample.txt","../doc/sample.txt").    
compare file 1: ../doc/sample.txt to file 2 ../doc/sample.txt
the 2 files have the same length
end of comparison
ok
4>