[R] Problem with writeBin and importing into gfortran compiled programs

Duncan Murdoch murdoch at stats.uwo.ca
Thu Jan 7 20:15:40 CET 2010


On 07/01/2010 2:05 PM, jgarcia at ija.csic.es wrote:
> Hi all,
> I'm having problems trying to export binary arrays from R and importing
> them into fortran (linux openSUSE 10.3 (x86_64), gfortran compiler,
> fortran 90/95 program).
>
> Let's say the problem can be expressed as:
>
> R part
> ------------
> >whini <- runif(1000)
> >writeBin(whini,"fwhini.dat")
>
> f90 part
> ------------
> PROGRAM foo
> INTEGER, PARAMETER :: DP = KIND(1.0D0)
> INTEGER :: status
> REAL(DP), DIMENSION(10,100) :: whini
> OPEN(UNIT=5, FILE='fwhini.dat', STATUS='OLD', ACTION='READ', &
>      FORM='UNFORMATTED', IOSTAT=status)
> READ(5) whini
> CLOSE(5)
> WRITE(*,*) whini
> END PROGRAM
>
> Now, if within the R session I check
>
> >typeof(whini)
> [1] "double"
>
> and try
>
> >whini.copy <- readBin("fwhini.dat",what=double(),n=1000)
>
> the copy of whini is right. However, execution of the fortran program
> gives the message:
>
> Fortran runtime error: Unformatted file structure has been corrupted.
>
> I've tried also to declare whini in the fortran part as SINGLE precision,
> and to force writeBin using the "size" argument.
> size=4 and size=8 give the same error (whini as double in the fortran
> part), while size=16 gives the alternative error
> "Fortran runtime error: I/O past end of record on unformatted file"
>
> Please, could you help me with this problem?
I've never used Fortran 90, so I can't tell if your type declaration is 
really declaring double precision values.
So what I'd do is to create an array (say the values 1 to 1000) within 
your Fortran program, and write it out.
Then do the same in R, and do a binary compare of the files to see what 
the differences are.  The things to look for are:

Size of values (4 or 8 bytes or something else).

Byte order within values (big or little endian).

R is very flexible in what it writes, and probably Fortran is flexible 
in what it can read, but you need to figure out what the differences are 
before you can match them up.

The viewRaw() function in the hexView package is a simple way to look at 
the bytes in the files.

Duncan Murdoch



More information about the R-help mailing list