views:

1752

answers:

2

Is there any way to figure out the length of a .dat file (in terms of rows) without loading the file into the workspace?

+7  A: 

I'm assuming you are working with text files, since you mentioned finding the number of rows. Here's one solution:

fid = fopen('your_file.dat','rt');
nLines = 0;
while (fgets(fid) ~= -1),
  nLines = nLines+1;
end
fclose(fid);

This uses FGETS to read each line, counting the number of lines it reads. Note that the data from the file is never saved to the workspace, it is simply used in the conditional check for the while loop.

gnovice
+2  A: 

It's also worth bearing in mind that you can use your file system's in-built commands, so on linux you could use the command

[s,w] = system('wc -l your_file.dat');

and then get the number of lines from the returned text (which is stored in w). (I don't think there's an equivalent command under Windows.)

djr

related questions