1

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');
3
  • Shouldn't your reading staement be pt(j) = fread(fid,1,'float',0,'a');. In your original statement, your variable a is in place of the skip parameter ... Commented Nov 14, 2018 at 17:46
  • @Hoki Nope, skip is optional. It does not matter. Commented Nov 14, 2018 at 18:11
  • I think I know what is going on here (certain enough to post an answer). But you might want to include how you open the file in your question. Commented Nov 14, 2018 at 18:14

1 Answer 1

7

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');
Sign up to request clarification or add additional context in comments.

2 Comments

wow, you are a champ Sir. It works. I was using 'rt' exactly like you described it. When I removed the 't'. It works like a charm. Thank you.
@Samer ... I would also recommend to follow his last advice, make the binary format explicit by using rb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.