2017-04-13 15 views
0

2つのバイナリファイルの違いを比較しようとしましたが、ファイルを読むときに1行ずつ比較するのは混乱します。 ({Xn, Yn}ペアの1つのリストに二つのリストを結合するためにzipファイルを():のような両方のファイルの最初の行を読んで、そしてその後、Erlangは2つのバイナリファイルを1行ずつ比較します

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)]). 
+0

次の2つのバイナリを比較するために、パターンマッチングを使用することができます。 –

+0

でも、別の値を表示する必要があります –

+0

2つのバイナリの違いを表示しますか? –

答えて

0
あなたがリストを使用することができます

を比較するために、両方のファイルの2行目を読んで、比較それらの長さが同じであることを確認してください)、結果をforeach()にリストします。

0

あなたは何をしたいのか、それまでに試したことについてもっと詳しく述べるべきです。

私は、比較を実行するコードの例に参加し、異なる行を行番号とともに出力し、1つのファイルが長い場合は残りの行を出力します。

私はバイナリをリストに変換しません。それは不要で非効率です。

-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> 
関連する問題