Problem with foef and fread in reading data from a binary file

7 Ansichten (letzte 30 Tage)
Hello,
I have a problem with feof in reading from a binary file.
I have a binary file contaning data. The file is built as follow: it has an head with some information (some integer and double) and then it starts with the data. The data have the following structure: there is an integer and the a bunch of double (I know from the head information the size of the bunch). This alternating structure repeats itself till the end of the file, clearly I don't know how many times. I've done the following while loop to read all the bunches of data:
i=0;
while ~feof(fid)
i=i+1;
integer(i,1)=fread(fid,1,formatint);
data(:,i)=fread(fid,bunch,formatdouble);
end
where formatdouble and formaint are respectively the format for double and for integer, defined previously in the code, and fid is the fileID
The problem is that the scripts doesn't exit from the while loop (it doesn't update the feof(fid) and send me back the following error:
Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is
0-by-0.
I understand that this error is due to the fact that it reaches the end of the file but it doesn't exit from the while loop.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 22 Nov. 2018
Bearbeitet: Walter Roberson am 22 Nov. 2018
feof does not reliably predict end of file . In some cases where reading to end of line can happen then feof can report end of file one interaction sooner than posix would mandate , but in cases where a specific number of elements are read, feof does not peak ahead to determine if more will be available .
Accordingly you should be testing whether the fread returns empty before assigning the results to an indexed variable .
  1 Kommentar
Antonio Desiderio
Antonio Desiderio am 22 Nov. 2018
Thank you,
I've done the following modification to the code and it works now
i=0;
testint=fread(fid,1,formatint);
while ~isempty(testint)
i=i+1;
integer(i,1)=testint;
data(:,i)=fread(fid,bunch,formatdouble);
testint=fread(fid,1,formatint);
end

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help 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