[SciPy-user] reading binary files written by a gfortran code...

Phil Austin phaustin@gmail....
Sun Jun 15 11:10:30 CDT 2008


fred wrote:
> Hi,
> 
> Ok, this is a well known issue that binary files written by a fortran 
> program have a "special" format.
> 
> So my question is : is it possible to write binary file _using gfortran_
> (no problem with intel fortran compiler) without this formatting ?

You want to write/read direct access files, which are just the bytes
without the compiler-specific recordlength information.  Here is
an example of a some tutorial code I wrote for myself exercising
memmap and a fortran direct-access read -- just replace read with
write in the fortran code to get output

1) write a test binary  data file in python with fortran layout and make
sure you can read it back in using mmemap

import numpy as np
xdim=4
ydim=5
zdim=6
theData=np.empty([xdim,ydim,zdim],dtype=np.int32)
for i in np.arange(xdim):
     for j in np.arange(ydim):
         for k in np.arange(zdim):
             theData[i,j,k]=100*(i+1) + 10*(j+1) + (k+1)
print theData
fortout=open('fortout.dat','w')
Cout=open('Cout.dat','w')
theData.tofile(fortout)
theData.tofile(Cout)
fortout.close()
Cout.close()
theFout = np.memmap('fortout.dat', dtype=np.int32,\
                     shape=(xdim,ydim,zdim), order='F')
theCout = np.memmap('Cout.dat', dtype=np.int32, \
                     shape=(xdim,ydim,zdim), order='C')
for i in np.arange(xdim):
     for j in np.arange(ydim):
         for k in np.arange(zdim):
             theFout[i,j,k]=theData[i,j,k]
             theCout[i,j,k]=theData[i,j,k]
theFout.sync()
theCout.sync()


2) and now read fortout.dat using standard f95 direct access:

program readfile
integer,parameter :: xdim=4,ydim=5,zdim=6
integer(kind=4):: thevar(xdim,ydim,zdim)
integer :: i,j,k,recnum
open(unit=12,file="fortout.dat",access="direct",action="read",recl=4)
recnum=0
do i=1,xdim
   do j=1,ydim
      do k=1,zdim
         recnum=recnum+1
         read(12,rec=recnum) thevar(i,j,k)
         print *,i,j,k,thevar(i,j,k)
      enddo
   enddo
enddo
close(unit=12)
end


More information about the SciPy-user mailing list