fwrite sometimes uses 5 bytes to write a 4-byte single

조회 수: 1 (최근 30일)
James Riehl
James Riehl 2011년 7월 26일
For me, the following code
fid = fopen('test.dat','wt');
x = single(1.28);
fwrite(fid,x,'single');
bytes = ftell(fid)
produces the result
bytes =
5
instead of the expected result
bytes =
4
which I get for most other values of x. The value of 1.28 is one example, but not an isolated case. In general, about 1 to 2 percent of values take 5 bytes instead of 4. For example,
fid = fopen('test.dat','wt');
x = single(rand(10000,1));
fwrite(fid,x,'single');
bytes = ftell(fid)
produces the result
bytes =
40127
Does anyone know what is going on here and why?

채택된 답변

Walter Roberson
Walter Roberson 2011년 7월 27일
If you want to use fwrite() you should not be opening the file as a text file ('wt'). Opening as a text file tells the file system to convert the line terminator.
>> typecast(single(1.28),'uint8')
ans =
10 215 163 63
10 happens to correspond to newline, so that is going to be converted to the byte sequence 13 10 215 163 63 (CR LF then some bytes)
When you are working with binary, leave the 't' off of 'rt' and 'wt'.
  댓글 수: 2
James Riehl
James Riehl 2011년 7월 27일
Thanks! I figured it was something simple, but I didn't realize 'wt' was specific for text.
Jan
Jan 2011년 7월 27일
@Walter: The next text-mode file access problem. I hope this strange feature (I do not claim that it is never useful) will disappear in the next 50 years...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by