Posts Tagged ‘ Fortran binary write sequential ’

Fortran and binary files: sequential access

When you write a binary (FORM=’UNFORMATTED’) file using Fortran 90, you have two choices:
1. Sequential access
2. Random access (or direct)

I will talk about the first method because the second one is easier to understand and is better documented in the web.
In the first method your program will open a file to write a 4-byte integer which contains the length of the record (i.e. the length in byte of the pieces of memory that you are writing on the disk), then it will write the block of memory (i.e. the variable) that you put in the “write” statement and then it will write the same 4-byte header that it wrote at the beginning of the file. The block of data between the integers is called record.  In the following example we will write two arrays in the same file using just one record (each time you call the write statement you write a new record on the file)

implicit none
integer, parameter :: N=8
real*8,dimension(N) :: U,V
integer :: i

do i=1,N
U(i)=i
V(i)=i
enddo

open(unit=2,FILE=’data.bin’,status=’replace’, &
FORM=’UNFORMATTED’)
write(2) U,V
close(2)

Now by using a hexadecimal editor like bvi or hexedit one can see what has really been written:


80 00 00 00 00 00 00 00 00 00 F0 3F 00 00 00 00 00 00 00 40
00 00 00 00 00 00 08 40 00 00 00 00 00 00 10 40 00 00 00 00
00 00 14 40 00 00 00 00 00 00 18 40 00 00 00 00 00 00 1C 40
00 00 00 00 00 00 20 40 00 00 00 00 00 00 F0 3F 00 00 00 00
00 00 00 40 00 00 00 00 00 00 08 40 00 00 00 00 00 00 10 40
00 00 00 00 00 00 14 40 00 00 00 00 00 00 18 40 00 00 00 00
00 00 1C 40 00 00 00 00 00 00 20 40 80 00 00 00

Each couple of numbers is a hexadecimal conversion of one byte (8 bit) in the file.
First look at this block “80 00 00 00” which is written both at the bottom and at the top of the file. That is the 4-byte integer that contains the length of the record. We have used 2 arrays made of 8 elements 8 byte long. So we expect to read a decimal 2*8*8=128, that is a hexadecimal 80 (8*16^1 + 0*16^0), which is exactly what we read.
But it is not over yet.
Let us use longer arrays, N=42. In this case we would expect that the header contains the following characters: 02 A0, that is 2*8*42=672. But on your hex-editor you might find: A0 02 00 00.
That is because your system is using little-endian ordering (that is the least significant bit first). On other systems you might find a big-endian ordering (most significant bit first).