Hi, I am trying to read in a formatted text file of unknown size. An example of the data I want to read in is shown below:
*lines 1-3: blank
*lines 4-6: useless text
*line 7: string string string double %(this line should be read into Settings)
*line 8: useless text
*lines 9-12: string double double string %(this line should be read into AlarmData)
*lines 13-16: blank
*line 17: string string %(this line should be read into Time)
This pattern then repeats throughout the entire file. My first thought was to determine the number of lines in the file so I used this code:
FileID= fopen(filename);
%Code to find number of lines in the file
assert(FileID~= -1, 'Could not read: %s', filename);
x= onCleanup(@() fclose(FileID));
count=0;
while ~feof(FileID)
count= count+sum(fread( FileID, 16384, 'char')==char(10));
end
fclose(FileID)
%code to determine number of data runs
num_data_runs=count/17;
I then try to loop through the file with textscan commands to read in the data to appropriate cells
FileID= fopen(filename);
iter=1;
while(iter<=num_data_runs)
Settings(iter,1:4)= textscan(FileID, '%s%s%s%f',1, 'headerLines', 6);
AlarmData(iter,1:4)= textscan(FileID, '%s %f %f %s',4, 'headerLines', 2);
Time(iter,1:2)= textscan(FileID, '%s%s', 1, 'headerLines', 4);
iter=iter+1;
end
fclose(FileID)
The result of this code is a 3x4 cell of AlarmData, a 3x4 cell of Settings, and a 3x2 cell of Time. The first row in all of these cells is what I intended them to be, but the other rows are all containing the wrong data from the file. Any thoughts?
Thanks

 Akzeptierte Antwort

Shameer Parmar
Shameer Parmar am 21 Jun. 2016

0 Stimmen

Consider you have text file with name 'Data.txt'.. then
Following command will give you all data present in text file.
Data = textread('Data.txt', '%s', 'delimiter', '')
and then..
NumberOfRows = length(Data);
to read the data row wise..
for count = 1:NumberOfRows
RowData = Data{count};
% add logic to perform any action on RowData.
end

2 Kommentare

Jenny May
Jenny May am 21 Jun. 2016
Ah, thank you. I don't know why I tried using a more complicated method. Will this code still work fairly quickly if my text file is thousands of lines long?
Shameer Parmar
Shameer Parmar am 22 Jun. 2016
Bearbeitet: Shameer Parmar am 22 Jun. 2016
Yes.. it will work for any text file of more than 1,00,000 lines of code..I already tried it...before posting my answer... :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by