function outstruct = read_structs_from_bin_file(fid,typestruct) % Matlab function to read a binary data file consisting of structs % usage : outstruct = read_structs_from_bin_file2(fid,typestruct) % % inputs: fid: file id obtained from fopen.m % % typestruct: structure to specify the type of each member, % example: % typestruct..type='double'; %can be 'int' 'uint8' etc, see fread.m % % if the member is an array, specify length as follows: % typestruct..length=1; % % optionally you can specify skip, if the data is padded with some empty bytes, see fread.m documentation % typestruct..skip=4; % % % outputs: outstruct: <1xn struct> where n is the number of times the % struct was printed to the file % % Rob Hoogendijk, 2013 %get members of the struct m=fieldnames(typestruct); n=length(m); %check properties of each member of the struct %if skip not specified, set it to 0 %if length not specified, set it to 1 for field_i=1:n fname=m{field_i}; %string containing the field name if ~isfield(typestruct.(fname),'skip') typestruct.(fname).skip=0; end if ~isfield(typestruct.(fname),'length') typestruct.(fname).length=1; end end %get data from file entry_i=0; outstruct=[]; while ~feof(fid) entry_i=entry_i+1; for field_i=1:n fname=m{field_i}; %string containing the field name size = typestruct.(fname).length; skip = typestruct.(fname).skip; precision = typestruct.(fname).type; [tmp,count]=fread(fid,size,precision,skip);%see fread.m documentation if(count>0)%to prevent creating an empty struct after the last data entry outstruct(entry_i).(fname)=tmp; end end end end%function