Docsity

Writing and Reading Files in Fortran: A Comprehensive Guide, Slides of Mechanical Engineering

Partial preview of the text

Download Writing and Reading Files in Fortran: A Comprehensive Guide and more Slides Mechanical Engineering in PDF only on Docsity!

MET 50

WRITING TO AND READING FROM FILES

  • To read from a file, we still use the READ statement.
  • To write output to a file, we use the WRITE statement.

READ (mm , nn) (things to write)

Tells us the FORMAT of what we read

Tells us where we read the input from

Example…

WRITE (25 , 16) X1, X2, X 16 FORMAT (1X, 3F10.2)

Also…

WRITE (mm , nn) X1, X2, X

  • “mm” and “nn” must be integer
  • WRITE (* , nn) directs output to screen

Files…

  • A file is like a book.
  • It needs to be opened, closed, flipped thru etc.
  • We have commands for this!

Opening a file…

OPEN (UNIT=mm,

FILE=“name of file”, STATUS=“OLD or NEW or replace”, ACTION=“READ or WRITE or READWRITE”, POSITION=“REWIND or APPEND or ASIS”, IOSTAT=integer number)

Simplified example…

OPEN (12, FILE=“temperature_data_1977.dat”,

STATUS=“OLD”, IOSTAT=IOS)

Code example…running this…

REAL :: DATE, TEMP add code here to generate some data to write! OPEN (12, FILE=“temperature_data_1977.dat”, STATUS=“NEW”, IOSTAT=IOS) WRITE (12,22) DATE, TEMP 22 FORMAT (1X, 2F12.4)

After you compile and run this code, you would find that the file “temperature_data_1977.dat” has appeared in your directory!

Two three more things…

(1) REWIND command

Sometimes we may need to :

OPEN a file READ the data READ it all again from the start

Code could include these lines…

OPEN (12, file=‘name.dat’, status=‘OLD’) READ (12,100) X,Y,Z 12 FORMAT (bla bla bla) do some calculations REWIND (12) READ (12,100) X,Y,Z do some more calculations CLOSE (12)

text data

Looks just like regular characters on the screen

IS readable!

Read: http://en.wikipedia.org/wiki/Data_file

Example…online (/121)

binary data

Looks unintelligible

Is NOT!

Example…online (/121)

Code would include lines like this…

OPEN (12, file=‘name.dat’, status=‘OLD’, form=‘unformatted’)

READ (12) X,Y,Z note no FORMAT statement!

and

WRITE (12) X,Y,Z ditto!

Large datasets often arrive in binary form.

A new paradigm in atmospheric science is “netCDF”