How to get the length of a file in MATLAB?

假如想象 提交于 2019-12-03 21:19:46

问题


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


回答1:


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



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/945006/how-to-get-the-length-of-a-file-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!