Skip to content

Problem with writeBin and importing into gfortran compiled programs

4 messages · Javier Garcia-Pintado, Duncan Murdoch, Berend Hasselman

#
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
------------
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
[1] "double"

and try
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?

Thanks,
Javier
---
#
On 07/01/2010 2:05 PM, jgarcia at ija.csic.es wrote:
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
#
jgarcia-2 wrote:
I am browsing in the Gfortran 4.3.0 manual.
On page 13 there is a mention of a record marker in unformatted files.
It could be that the fortran read is expecting a record marker every so many
bytes.
writeBin most likely has not written  any record marker.

In Fortran 2003  there is a new specifier ACCESS='STREAM'  (similar to Lahey
Fortran ACCESS='TRANSPARENT')(see page 23 of said manual) which will allow
reading files with no record structure.

Berend
#
Solved!!
Berend's suggestion to use ACCESS='STREAM' is perfect. I've checked that
it's even acepted by gfortran coming along with GCC 4.2.1 (the one I've
got), and solves the problem.

I was working around this through seek() and truncate(), but this is
clearly the star option!

Thanks Berend and Duncan,
Javier
---