How to get file length in MATLAB?

Is there a way to determine the length of a .dat file (in terms of lines) without loading the file into the workspace?

+4
source share
3 answers

Line counter - loads only one character per line:

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); 
+18
source

I assume that you are working with text files since you mentioned searching for the number of lines. Here is one solution:

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

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

+12
source

It's also worth keeping in mind that you can use the built-in file system commands, so on linux you can 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 is an equivalent command under Windows.)

+3
source

Source: https://habr.com/ru/post/1285674/


All Articles