2
votes

I am a newbie in fortran.

I made a program using the Microsoft Developer Studio 4.0 to create a binary file. I open it as follows:

      OPEN(2,FILE='output_bin.bin',FORM='UNFORMATTED')

I write in it an array INTEGER*2 IHIST(30), right now filled with numbers from 0 to 29. The writing is done with:

      DO 351 J=0,29
      WRITE(2) IHIST(J)
351   CONTINUE

In Windows I can read the binary file produced. I can recover the array.

Then I want to read it in Ubuntu. Here, is where I get my problem: I get Fortran runtime error: End of file, when I do the following:

     INTEGER*2 RBIN(30)
     WRITE(*,*)'Extracting data from binary file ', filename
     OPEN(3,FILE=filename,FORM='UNFORMATTED',ACTION='READ'
 +   ,STATUS='OLD')

     DO 17 I=0,29
     READ(3) RBIN(I)
17   CONTINUE

Can someone explain to me how I can read a sequential, unformatted binary files. What am I doing wrong? I thought the starting position for the next reading would be the end of the later.

I am using GNU Fortran (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2 to compile in Ubuntu 12.04.

1
1) unformatted fortran is simply not portable. Use streams or direct access. 2) fortran array indices start at 1 not 0. 3) integer*2 is not any standard type. - agentp
Are you learning old Fortran or trying to interpret an old code? If you're just now learning, you should be learning Fortran 95 syntax. And @george is right, the binary files just don't transfer from Windows to Linux. - dwwork
Hello, the binary files are produced by an old program and I have to change also a old program to be able to read them. - Andrea Larisi
I shouldn't, but is it possible? Or is out of the question? Are there any foreseen errors in the data transfer that I cannot deal with? - Andrea Larisi
Most Fortran implementations on Windows and Linux use the same on-disk layout for sequential, unformatted files, as long as your records don't go over 1GB, but you need to pay attention to big-endian vs. little-endian if you also change hardware architecture. Use of ACCESS='STREAM' would give you a "stream of bytes" without a record structure. - Steve Lionel

1 Answers

3
votes

Open a writable stream access file like this:

      OPEN(2,FILE=filename,FORM='UNFORMATTED',
     +     ACCESS='STREAM',STATUS='REPLACE')

Then read it like this:

      OPEN(3,FILE=filename,FORM='UNFORMATTED',
     +     ACCESS='STREAM',STATUS='OLD')

You should not have any problems if you (e.g.) write it on a x64 Linux platform compiled by gfortran, and read it on a Windows PC compiled with Intel Fortran. However, you may have problems if you read/write on different platforms with different endiannesses (e.g. POWER5 vs x64).