binary i/o files


sonu84
02-16-2009, 05:33 PM
Hi

I am trying to write a data file which stores the contents of an array. I am able to store the values in an ASCII format. I would like to store it in a binary format, hence can someone please let me know how to read and write binary files in fortran 90

Thanks

davekw7x
02-17-2009, 04:31 PM
...how to read and write binary files in fortran ...

!
! Write a binary file with gfortran
!
! davekw7x
!
program BinaryWriter

implicit none

real x
integer i

open(unit=8,file='gfortran.bin', form='UNFORMATTED',ERR=1000)

x=1.0
do i=1,40
x = x * 2.0
write(8,ERR=1001)i, x
enddo

write(*,'("Number of lines written = ", I5)', ERR=1001) i-1
stop

1000 write(*,'(" Error opening file for writing.")')
stop

1001 write(*,'(" Error writing with i = ", I5)') i
stop

end program BinaryWriter




!
! Read a binary file with gfortran
!
! davekw7x
!
program BinaryReader

implicit none

integer intvalue
real realvalue

integer i

open(unit=8,file='gfortran.bin',form='UNFORMATTED' ,status='OLD')

i = 1
do
read(8,END=999,ERR=1000) intvalue, realvalue
write(*,'(I5, ": ", 1PE13.6)') intvalue, realvalue
i = i + 1
enddo

999 write(*,'(/"End-of-file when i = ",I5)') i
stop

1000 write(*,'(/"ERROR reading when i = ",I5)') i
stop

end program BinaryReader



Output from BinaryReader when reading the file created by BinaryWriter (GNU gfortran 4.1.2 on Centos 5.2 Linux):

1: 2.000000E+00
2: 4.000000E+00
3: 8.000000E+00
4: 1.600000E+01
5: 3.200000E+01
6: 6.400000E+01
7: 1.280000E+02
8: 2.560000E+02
9: 5.120000E+02
10: 1.024000E+03
11: 2.048000E+03
12: 4.096000E+03
13: 8.192000E+03
14: 1.638400E+04
15: 3.276800E+04
16: 6.553600E+04
17: 1.310720E+05
18: 2.621440E+05
19: 5.242880E+05
20: 1.048576E+06
21: 2.097152E+06
22: 4.194304E+06
23: 8.388608E+06
24: 1.677722E+07
25: 3.355443E+07
26: 6.710886E+07
27: 1.342177E+08
28: 2.684355E+08
29: 5.368709E+08
30: 1.073742E+09
31: 2.147484E+09
32: 4.294967E+09
33: 8.589935E+09
34: 1.717987E+10
35: 3.435974E+10
36: 6.871948E+10
37: 1.374390E+11
38: 2.748779E+11
39: 5.497558E+11
40: 1.099512E+12

End-of-file when i = 41

Important Note: Programs like these can be compiled with just about any compiler for Fortran 77, Fortran 90, Fortran 95, etc.

However...

Binary files written like this may not be able to be read by programs compiled with other compilers---not even later versions or earlier versions of the same compiler!

For example, binary files written by GNU g77 (or just about any other Fortran that I have heard of) can not be read with GNU gfortran compilers earlier than 4.2 (version 4.1.something is supplied in RedHat EL5 and Centos 5 Linux distributions, among others), but they are compatible with GNU gfortran 4.2.x (supplied in recent Fedora and Ubuntu distributions, among others).

Bottom line: With Fortran binary files: Your Mileage May Vary! Really.

Regards,

Dave