%if length equal to 0, two files are compare from begin to end

function diff_num = compare_file(Filename1, Filename2, length)

diff_num = 0;

f1 = fopen(Filename1, 'r');
f2 = fopen(Filename2, 'r');

[buf1, count1] = fread(f1);
[buf2, count2] = fread(f2);

if (length>count1 | length>count2)  %length is too large
    disp(sprintf('at least one file length is not enough, 1st file length: %d bytes, 2nd file length: %d bytes', count1, count2));
elseif length == 0 %two files are compare from begin to end
    if count1~=count2
        disp(sprintf('lengths of two files are different, 1st file length: %d bytes, 2nd file length: %d bytes', count1, count2));
    else
        disp(sprintf('lengths of two files are: %d bytes', count1));
        for i = 1:count1
            if buf1(i)~=buf2(i)
                diff_num = diff_num + 1;
                disp(sprintf('the %dth difference located at %dth byte: %X(%d) in file1, %X(%d) in file2', diff_num, i, buf1(i), buf1(i), buf2(i), buf2(i)));
            end
        end
    end
else    %compare two files with the specified length
    for i = 1:length
        if buf1(i)~=buf2(i)
            diff_num = diff_num + 1;
            disp(sprintf('the %dth difference located at %dth byte: %X(%d) in file1, %X(%d) in file2', diff_num, i, buf1(i), buf1(i), buf2(i), buf2(i)));
        end
    end
end
    
fclose(f1);
fclose(f2);

