MATLAB: Deteriming number of bytes in one line of binary file

binary filesdata readingfortranMATLAB

I am working on translating some old fortran code into MATLAB and have run across the following issue.
In the fortran file I am working with the following check is performed
c This is read from another file but I'll just hard code it for now
NPX = 1024
NLN = 1024
open(unit=10, file=pictfile, access='direct', recl=2*npx, status='old')
read(10,rec=nln, err=20) inline(1:2*npx)
go to 21
20 bytes=1
21 continue
where nln is the number of lines in the file being read, and npx is the number of integers contained in each line. This check basically determines whether each of those integers is 1 byte or 2 bytes by trying to read in a line of 2 bytes for each integer, and then adjusting to 1 byte if there is an error. I understand the fortran code well enough to figure that out, but now I need to figure out how to perform this check in MATLAB. I have tried using the fgetl command on the file and then reading the length of the characters contained but the length never seems to be more than 4 or 5 characters, when even if each integer is 1 byte the length should be somewhere around 1000.
Can someone help me with devising some way to perform this check in MATLAB? I've thought about maybe a try-catch statement but I'm not very familiar with them and don't really know where to start.
Thanks! Andrew

Best Answer

For anyone else who may have this problem I believe I figured out a solution using try-catch statements.
I realized that all the above was doing was trying to read the data from the last record in the file. It was set up that if there was an error (it ran out of data in the file) it would kick out and set the number of bytes to 1 instead of 2. In order to do this in Matlab use the following:
fullpath=which(file); %extracting the full file path
s=dir(fullpath); %extracting information about hte file
fid=fopen(file_name,'r'); %opening image file
if s.bytes/NLN==2*NPX %if the file is NLN*NPX*2 bytes
for n=1:NLN %for each line

dn(n,:) = (fread(fid, NPX, '*uint16','b'))'; %reading in lines into DN

elseif s.bytes/NLN==NPX %Else if the file is NLN*NPX bytes
for n=1:NLN %for each line
dn(n,:) = (fread(fid, NPX, '*uint8','b'))'; %reading in lines into DN
else %If the file is neither something went wrong
error('Invalid file. The file is not the correct size specified by the SUM file')
hope this helps, but be careful! This only works if all of the data in the file is the same type (ie uint8 or uint16) and you know the number of entries that should be contained in the file beforehand. Andrew