MATLAB: Read file with ascii characters and binary data on one single line

asciibinaryfileMATLABread

Hi,
I need to read data from a file which consists of approximately 1000 lines of ascii header and then a line consisting of the delimiter "#!" and the data in the file (written in binary data (Int32)). I can read the header using fgetl(fid) and also identify the delimiter, but when trying to continue reading from there using fread(fid,3,'int32') the values are non-sense. Do I somehow loose the reading position?
If I cut the delimiter and the header of the file using a text editor, I can read the purely binary file with fread(fid,3,'int32'). But I would like to speed it up without manually manipulating the file. Any suggestions? Thanks a lot!
So far I'm trying this:
fn='test.nid';
fid = fopen(fn, 'r', 'ieee-be');
stillheader=1;
while stillheader
% store the current position in file
headerendpos_ascii=ftell(fid);
oneline=fgetl(fid);
k=k+1;
if isempty(strfind(oneline,'#!')) % it's not yet the delimiter
% read relevant data from header ...
else
stillheader=0;
end
end
% now read the delimiter and the binary data
fseek(fid,headerendpos_ascii,'bof'); % move to beginning of line with delimiter
test=textscan(fid,'%c',2) % read the delimiter, now we are behind the delimeter #!
binarydata=fread(fid,200,'int32'); % read the first 200 valkues of the binary data.
fclose(fid)

Best Answer

As noted in the comment, it's bizzaro way to have done, but the following seems to work...
>> l=fgetl(fid);while ~contains(l,'#!'), l=fgetl(fid);end % get to the delimeter line...
>> fseek(fid,-numel(l)+1,'cof'); % backup to just past the #!
>> fread(fid,3,'*int32')
ans =
3×1 int32 column vector
47465896
49587076
45505136
>>
These aren't quite the same values as OP says, probably he's looking at a different file than the one he posted.
NB: The position after the while loop will be dependent on the data content -- fgetl won't terminate until if finds a two-byte sequence that qualifies as line terminator and it'll be dependent upon the actual data values where that is. So, back up the number of bytes in the last read and the offset of the two terminator bytes that offset the two indicator characters and add one. This is dependent upon the Windows convention which it appears the file follows.
It would be more robust to do the read on a character-by-character basis or, (as I think G?) suggested suck it all up as char() and do a text search for the magic character string and then decode the rest from that point.