How to get the length of a file in MATLAB?

2020-03-04 08:11发布

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

3条回答
叛逆
2楼-- · 2020-03-04 08:42

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.)

查看更多
迷人小祖宗
3楼-- · 2020-03-04 08:59

Row Counter -- only loads one character per row:

Nrows = numel(textread('mydata.txt','%1c%*[^\n]'))

or file length (Matlab):

datfileh = fopen(fullfile(path, filename));
fseek(datfileh, 0,'eof');
filelength = ftell(datfileh);
fclose(datfileh);
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-03-04 09:06

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.

查看更多
登录 后发表回答