を役に立てば幸いで合成したサンプルの問題である:私は私が解析したいバイナリファイル(test.txtという)を持っています。私は<<$a, $b, $c>>
のすべてのバイナリパターンをファイル内に見つける必要があります。
"test.txtの" の内容:
I arbitrarily decide to choose the string "abc" as my target string for my test. I want to find all the abc's in my testing file.
サンプルプログラム(lab.erl):
-module(lab).
-compile(export_all).
find(BinPattern, InputFile) ->
BinPatternLength = length(binary_to_list(BinPattern)),
{ok, S} = file:open(InputFile, [read, binary, raw]),
loop(S, BinPattern, 0, BinPatternLength, 0),
file:close(S),
io:format("Done!~n", []).
loop(S, BinPattern, StartPos, Length, Acc) ->
case file:pread(S, StartPos, Length) of
{ok, Bin} ->
case Bin of
BinPattern ->
io:format("Found one at position: ~p.~n", [StartPos]),
loop(S, BinPattern, StartPos + 1, Length, Acc + 1);
_ ->
loop(S, BinPattern, StartPos + 1, Length, Acc)
end;
eof ->
io:format("I've proudly found ~p matches:)~n", [Acc])
end.
を実行し、それ:
1> c(lab).
{ok,lab}
2> lab:find(<<"abc">>, "./test.txt").
Found one at position: 43.
Found one at position: 103.
I've proudly found 2 matches:)
Done!
ok
上記のコードはあまり効率的ではないことに注意してください(スキャンプロセスは一度に1バイトずつシフトします)、シーケンシャル(コンピュータ上のすべての「コア」を使用しない)です。それは単にあなたを始めさせることを意味します。
これはまた、解析しようとしているバイナリの例と最終結果がどのように表示されるかを助けます。 – Lukas