Why does FEOF return false when opening an empty text file in 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);

 Accepted 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);

1 Comment

For C++ there are arguments to be made that it should be referred to as the ISO spec rather than the ANSI spec. ANSI X3J16 committee formally adopted ISO/IEC 14882:1998 which was a joint effort between ANSI X3J16 and ISO WG21.
My guess is that formally you are relying on POSIX's definition of feof() via IEEE 1003.1, which in turn defers to ISO C rather than to ANSI C.
Not that it really matters except to some of us old-timers who lived and breathed K&R ;-)

Sign in to comment.

More Answers (0)

Categories

Products

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!