Samer
Samer

Reputation: 1980

how to read binary format byte by byte in MATLAB

I have been struggling with this bug. When using MATLAB to read a binary file that contains three columns of numbers in float formats.

I am reading one number at a time using this line.

    pt(j) = fread(fid,1,'float','a');

I have found that sometimes (rarely) MATLAB instead of reading four bytes for a float, it uses 5 bytes. And it misses up the rest of the reading. I am not sure if the file is corrupted or MATLAB has a bug there. When I printed the file as a txt and read it in txt everything works well.

As a work around here is what I did:

cur = ftell(fid);
if (cur - prev)~= 4
      pt(j) = 0; % I m throwing this reading away for the sake of saving the rest of the data. This is not ideal 
      cur = prev +4;
      fseek(fid, cur,'bof');
end
prev = cur; 

I tried different combinations of different formats float32 float64 etc... nothing works MATLAB always read 5 bytes instead of 4 at this particular location.

EDIT: To solve it based on Chris's answer. I was using this command to open the file.

fid = fopen(fname,'rt');

I replaced it with this

fid = fopen(fname,'r');

Upvotes: 1

Views: 631

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60780

Sometimes, rarely, skipping a byte. It sounds to me like you are on Windows, and have opened the file in text mode. See the permissions parameter to the fopen function.

When opening a file in text mode on Windows, the sequence \r\n (13,10) is replaced with \n (10). This happens before fread gets to it.

So, when opening the file, don't do:

fid = fopen('name', 'rt');

The t here indicates "text". Instead, do:

fid = fopen('name', 'r');

To make this explicit, you can add b to the permissions. This is not documented, but is supposed to mean "binary", and makes the call similar to what you'd do in C or in the POSIX fopen():

fid = fopen('name', 'rb');

Upvotes: 7

Related Questions