tags:

views:

319

answers:

3

Simple question: I am opening a file in matlab 7.x, and I want to test if it is empty before reading it. What's the best way to do this?

A: 

got it:

fid = fopen(fil);
if all(fgetl(fid) == -1)
  % file is empty
else
  fseek(fid,0,-1); % rewind it
end
johndashen
If it's a binary file, `fgetl` might behave oddly.
mtrw
+5  A: 

Taking some knowledge from this previous question, I would do the following

s = dir('c:\somefile.txt');
if s.bytes == 0
    % empty file
else
    % open the file and read it
end;

I assumed by empty that you meant that there is really nothing in the file including new line characters. If by empty you mean only new line characters, then you should go ahead with your solution.

Justin Peel
I did mean empty as in nothing. This is what I was looking for, thanks.
johndashen
@johndashen Glad I could help.
Justin Peel
A: 

This is the cleanest way I can think of:

if fseek(fileID, 1, 'bof') == -1
   % empty file
else
   rewind(fileID)
   % ready to read
end
AVB