how to read binary file generated by Fortran
조회 수: 5 (최근 30일)
이전 댓글 표시
Hi there,
I have a binary file created by Fortran as following:
open(199,file='arrival.bin',form='unformatted')
write(199) data
The data contains 20k lines of float data (such as 394.06663, 395.03748, ...).
I did some research that using fread could load the file. However I used the following lines, it's not working.
fid = fopen('arrival.bin','rb');
A = fread(fid,20000,'single');
fclose(fid);
Please help me. I appreciate that in advance.
댓글 수: 4
답변 (2개)
James Tursa
2019년 3월 27일
편집: James Tursa
2019년 3월 27일
Unformatted Fortran is not the same as stream binary. Whereas stream binary is just the data itself, unformatted Fortran has extra bytes inserted in the file along with your data ... what is there is compiler dependent and you often have to poke around a bit to find out. You need to read and discard those extra bytes. E.g., to read the beginning of the file:
% File arrtimes.m
fid = fopen('arrtimes.bin','rb');
discard = fread(fid,[1 1],'*int32')
x = fread(fid,[10 1],'*double')
fclose(fid);
And a sample run with your file:
>> arrtimes
discard =
8
x =
224.9656
0.0000
229.1356
0.0000
233.5438
0.0000
238.0880
0.0000
242.8081
0.0000
So, my code isn't quite matching up with your data since I am seeing double precision values not singles, and there are 0's in the result. Those 0's could easily be extra bytes written by Fortran and not your data, however. So maybe all you need to do is this:
fid = fopen('arrtimes.bin','rb');
discard = fread(fid,[1 1],'*int32'); % discard the beginning bytes
x = fread(fid,inf,'*double'); % read everything in
x = x(1:2:end); % discard those 0's
fclose(fid);
And after a run:
>> x(1:15)
ans =
224.9656
229.1356
233.5438
238.0880
242.8081
247.7140
252.8079
258.0908
263.5653
271.6778
287.4983
303.3301
319.1987
335.1084
351.0560
댓글 수: 2
Walter Roberson
2019년 3월 27일
Probably the most common for Unformatted Fortran binary is for there to be a 4 byte record length at the beginning and also the end of each record. Both sides was for historical reasons to permit tape drives to move backwards by record.
참고 항목
카테고리
Help Center 및 File Exchange에서 Fortran with MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!