MATLAB: How to get the final number of lines in a data file

MATLAB

Hi all, I have a data file as follow:
x 0 y 1
x 1.3 y 2.2
x 2.2 y 6
x 3.4 y 7.4
I need to read into this file, plot the data (which is done) and put the number of lines in the title of the plot. I uses the following code to get the number of lines:
count = 0;
while ~feof(fid)
count = count+1
end
however, as it is in a while-loop, the 'count' changes every time:
count =
1
count =
2
count =
3
count =
4
how to get a FINAL number of lines ? (aka, I want count = 4 and only =4, not varying during each time the loop running). as I need to put this 'final' number into title.
Thank you very much.

Best Answer

count = 0;
while true
if ~ischar( fgetl(fid) ); break; end
count = count + 1;
end
fclose(fid)
title(sprintf('lines in file = %d', count));
Note that feof(fid) never predicts end of file. feof() is never true unless you have already tried to read after the end of file, so even with a completely empty file, feof() would not immediately be true.
You can tell you have reached end of file when fgetl() returns something that is not a character.