MATLAB: Does FEOF return false when opening an empty text file in MATLAB

MATLAB

I am using the following code to read a text file line by line. I have noticed that if the file is empty, FEOF returns a 0 and I run through the loop at least one time.
fid = fopen('foo.txt');
while ~feof(fid)
s=fgetl(fid);
% do something with s
end
fclose(fid);

Best Answer

This behavior comes from the ANSI spec for C/C++'s "feof". FEOF does not return true until you actively read past the end of the file. This means that even after reading the last byte of a file, FEOF would return false. It would only return true if you then tried to read another byte.
As a result a better way to read the file is:
fid = fopen('foo.txt');
s=fgetl(fid)
while ~feof(fid)
% do something with s
s=fgetl(fid)
end
fclose(fid);