MATLAB: How to compare two files line by line

files compare

I want to compare two files line by line and count how many lines they have in common , I tried the code below , but it doesn't work , somehow MATLAB stops working , ">>" just disappear
f = fopen('nv.txt','at');
fid = fopen('test.txt');
k = 0;
while ~feof(fid)
s1 = fgetl(fid);
if ~isempty(s1)
while ~feof(f)
s2 = fgetl(f);
if ~isempty(s2)
if(strcmp(s1,s2))
k = k+1;
end
end
end
end
end
fclose(fid);
fclose(f);
disp(k);

Best Answer

f = fopen('nv.txt');
fid = fopen('test.txt');
k = 0;
while ~feof(fid)
s1 = fgetl(fid);
frewind(f) % start from the first line of the second file
if ~isempty(s1)
while ~feof(f)
s2 = fgetl(f);
if ~isempty(s2)
if(strcmp(s1,s2))
k = k+1;
end
end
end
end
end
fclose(fid);
fclose(f);
disp(k);