IRI
Data Library
Finding Data
Mastering the Data Library
help@iri
Search

Reading Data Files in FORTRAN

netCDF files

To write a fortran program to read netCDF files, you need to link to the netCDF library. This library has some tools as well, including ncdump and ncgen, which together can generate C or FORTRAN code to read a particular netCDF file.

We also have a library ODB, which is a greatly simplified interface to the netCDF library.

Direct Access files

Direct access (or random access) files are pure data files: they contain the binary data and do not contain any formatting information. The ordering of the data is determined by how the file was written, but the data can be read back in whatever size chunk is most useful.

For example, consider a random-access file that contains a three dimensional dataset: 360 by 180 by 12. To read the data as a single chunk from a file called 'evap',

      program rea
      parameter(NX=360,NY=180,NT=12)
      real evap(NX,NY,NT)
      open(1,file='evap',form='unformatted',
     * status='unknown',access='random',RECL=NX*NY*NT)
      read(1,REC=1)evap
      stop
      end
OR (just to give you practice in reading data in pieces)
      program rea
      parameter(NX=360,NY=180,NT=12)
      real evap(NX,NY,NT)
      open(1,file='evap',form='unformatted',
     * status='unknown',access='random',RECL=NX*NY)
      do IT=1,NT
         read(1,REC=IT)((evap(i,j),i=1,nx),j=1,ny)
      enddo
      stop
      end
The point being that, for random access files in fortran, you need to specify the record length in the open statement, and the record number in the read (or write) statement. Some machines give the RECL in words (my machine and my example), others have the RECL in bytes, in which case you would have in the second example
      open(1,file='evap',form='unformatted',
     * status='unknown',access='random',RECL=4*NX*NY)
Some machines call it access='direct', instead.

Text files

To read a text file in FORTRAN, I highly recommend using star-formatted reads.
       read(5,*) evap
This reads blank-delimited data, and will keep reading new lines of text until the array is filled.