Reading varying headerlines length, text files
3 views (last 30 days)
Show older comments
Hi, I am trying to read specific part of the header lines for these files and once I read lines i want to increment for each block and display them into GUI edit text boxes.
fid= fopen([FilesToRead, MultipleFiles]);
textForGUI = cell(1);
while true
tLine = fgetl(fid);
headerCells = strsplit(tLine,' ');
if length(headerCells) > 1
if ~isempty(headerCells{2})
if ~strcmpi(headerCells{2},'!User') && ~strcmpi(headerCells{2},'data')
textForGUI(end+1) = headerCells(2);
else
break
end
end
end
end
textForGUI = textForGUI(2:end);
Block=0;
while true
tLine = fgetl(fid);
if ~ischar(tLine)
break;
end
if ~isempty(strfind(tLine,'data'))
Block=Block+1;
if true
% code
end
formatSpec = '%f %f %f %f %f';
C = textscan(fid,formatSpec,24,'CommentStyle','data','Delimiter','\t');
%here I got some calculations and plots
end
end
Thanks!
Accepted Answer
Kelly Kearney
on 23 Aug 2016
I usually find the easiest way to do this sort of thing is to read the whole file in as plain text (assuming it's not too large), and then parsing out the bits I want using strfind and regexp as appropriate. Here's an example:
fid = fopen('~/Downloads/Example-2.txt');
tmp = textscan(fid, '%s', 'delimiter', '\n', 'whitespace', '');
tmp = tmp{1};
fclose(fid);
% Figure out where each header section begins and ends
sidx = find(~cellfun('isempty', regexp(tmp, '^\d*\s*\*\*\*letter')));
eidx = find(~cellfun('isempty', regexp(tmp, '^\d*\s*high')));
% Assume data runs from end of one header to beginning of next
dsidx = eidx + 1;
deidx = [sidx(2:end)-1; length(tmp)];
% Loop over blocks
nblock = length(sidx);
C = cell(nblock,1);
textForGUI = cell(nblock,1);
for ii = 1:nblock
% Read the header block and data block
headerlines = tmp(sidx(ii):eidx(ii));
datalines = tmp(dsidx(ii):deidx(ii));
% Throw away the data lines you don't need (!user, data, blank)
datalines = regexprep(datalines, '^\d*', '');
isgood = cellfun('isempty', strfind(datalines, '!user')) & ...
cellfun('isempty', strfind(datalines, 'data')) & ...
~cellfun('isempty', strtrim(datalines));
datalines = sprintf('%s\n', datalines{isgood});
% Read numbers from cleaned-up data block
formatSpec = '%f %f %f %f %f';
C{ii} = textscan(datalines,formatSpec,24,'CommentStyle','data','Delimiter','\t');
textForGUI{ii} = headerlines(2:end);
end
0 Comments
More Answers (0)
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!