72
Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University [email protected]

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Embed Size (px)

DESCRIPTION

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University [email protected]. Summary of Part 3. Program Units: Subroutines Functions Modules Common Blocks Include Statements More on Pointers Input/Output and File Handling. Program Units. - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Introduction to

Fortran95 Programming

Part III

By Deniz Savas, CITI, Clemson University

[email protected]

Page 2: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Summary of Part 3

• Program Units:

Subroutines

Functions

Modules

Common Blocks

Include Statements

• More on Pointers

• Input/Output and File Handling

Page 3: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Program Units

• Main Program

• External Procedures− Subroutines

− Functions

• Internal Procedures − Subroutines

− Functions

• Modules

• Common Blocks

Page 4: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Program Structure

[PROGRAM [program_name] ]

[ Data specification & declaration_statements]

[executable_statements]

[contains]

[internal_procedures]

END [ PROGRAM [program_name]

Page 5: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Main program containing internal procedure(s)

[PROGRAM [program_name] ]

[ declaration_statements]

executable_statements

CONTAINS

[ internal procedure(s)]

:

END [ PROGRAM [program_name] ]

! Note that everything is contained in one file.

Page 6: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Main program containing external procedure(s)

[PROGRAM [program_name] ]

[ declaration_statements]

executable_statements

END [ PROGRAM [program_name] ]

[procedure]

:

[procedure]

! Procedure= function or subroutine.

! Note that procedures can be contained in separate files.

Page 7: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Procedures

• There are two types of procedures, namely SUBROUTINE and FUNCTION

• The only difference between a subroutine and a function is that a function returns results as its value.

• There is no specification difference between internal and external procedures.

• Functions are utilised by referencing their name in an expression where as subroutines are CALL’ed.

Page 8: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

A typical program structure with internal procedures.

PROGRAM declarations

executable statementsCONTAINS SUBROUTINE abc (… ) declarations executable statements

END SUBROUTINE def(…)

declarations executable statements END FUNCTION ghi( … ) declarations

executable statements ENDEND

Page 9: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

A typical program structure.

PROGRAM

declarations

executable statements

END

SUBROUTINE abc (… )

declarations

executable statements

END

SUBROUTINE def(…)

declarations

executable statements

END

FUNCTION ghi( … )

declarations

executable statements

END

Page 10: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Subroutines

SUBROUTINE name [ ( argument_list ) ]

declaration

executable statements

END

EXAMPLE:

SUBROUTINE FILTER ( VOLTAGE, CURRENT)

REAL , INTENT(IN) :: VOLTAGE

REAL,INTENT(INOUT) :: CURRENT

executable_statements

END

Page 11: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Functions

[type] FUNCTION name [ ( argument_list ) ]

declaration

executable statements

END

EXAMPLE:

REAL FUNCTION ENERGY ( MASS, VELOCITY)

REAL , INTENT(IN) :: MASS , VELOCITY

ENERGY = MASS*VELOCITY*VELOCITY

END

Page 12: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Using Subroutines and Functions

• Assuming the declarations in the previous two slides, the following are valid statement which use these procedures.

REAL :: VOLT(10) , CUR(10)

REAL :: MASS,V , A , ENERGY

DO I = 1, 10

CALL FILTER(V(I) , CUR(I) )

END DO

A = SQRT(MASS)*ENERGY(MASS,V )

Page 13: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Scope of Variables

The rules governing this ‘Referability’ is called the scoping rules. For any variable or label scoping rules define the parts of the program where this item is visible.

Variables declared within a program or subroutine or function (referred to as ‘program units’) are accessible from anywhere within that program unit and also other program units CONTAIN’ed within it.

Page 14: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Scope of Variables

PROGRAM TEST

REAL :: BASE ,X(10) ,Y(20)

BASE = 123.4

CALL NORMALISE(X)

CALL NORMALISE(Y)

CONTAINS

! Thus the subroutine is internal to program test ….

SUBROUTINE NORMALISE(ARRAY)

REAL :: ARRAY(:)

ARRAY = ARRAY/BASE

END SUBROUTINE NORMALISE

END PROGRAM TEST

All variables BASE, X and Y are available for use in subroutine NORMALISE.

Page 15: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Scope of Variables continued …

PROGRAM test REAL :: BASE ,X(10) ,Y(20) BASE = 123.4 CALL NORMALISE(X) CALL NORMALISE(Y)END program test

SUBROUTINE NORMALISE(ARRAY) REAL :: ARRAY(:) ARRAY = ARRAY/BASEEND subroutine normalise

None of the variables BASE,X or Y are available in the subroutine NORMALISE. Because BASE is not available, this program will not work!

Page 16: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

When should I use Internal Procedures

• PREFER AN INTERNAL PROCEDURE;

− If it is needed to be called from only one program unit.

− If you are accessing a lot of variables which will make the argument list rather large.

− If you do not want that routine to be available from any other routine.

• Otherwise use the EXTERNAL form

Page 17: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Subroutine & Function Arguments

Arguments enable data exchange between the calling/ invoking and the called/invoked subroutine/function.

The way the data is exchanged can be specified more precisely by the following keywords.

• Intent : Defines the ability to modify the arguments.

• Keyword : Enables us to pass arguments in an order independent way.

• Optional : Allows us to make some arguments optional.

• Recursive, Result : Needed for recursive invocation.

Array valued functions allow array values to be returned.

Page 18: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

The Use of INTENT Attribute

SUBROUTINE DISTANCE( P1 , P2 , DIST,N)

INTEGER , INTENT(IN) :: N

REAL ,INTENT(IN) :: P1(N) , P2(N)

REAL , INTENT(OUT) :: DIST

DIST = 0.0

DO I = 1 , N

DIST = DIST + ( P1(I) -P2(I) ) **2

END DO

DIST = SQRT ( DIST )

RETURNEND

Page 19: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

INTENT Examples cont.

REAL FUNCTION SWAPNSUM ( A , B )

REAL , INTENT(INOUT) :: A , B

REAL :: TEMP

TEMP = A

A = B

B = TEMP

SWAPNSUM = A + B

END

Page 20: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Using Keyword & OPTIONAL Arguments

INTERFACE

SUBROUTINE GETDET ( AREA , DENSIT ,C , D , ELEV )

REAL, OPTIONAL,INTENT(INOUT) :: AREA,DENSIT,C,D,ELEV

END SUBROUTINE GETDET

END INTERFACE

:

CALL GETDET ( X,Y,Z,W,Q )

CALL GETDET ( X,Y, ELEV=Q,D=W, C=Z)

CALL GETDET ( AREA=X,DENSIT=Y ,ELEV=Q ,C=Z,D=W)

! All above three calls are identical in effect.

Page 21: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Optional ArgumentsCALL GETDET(V,W, X,Y,Z )

CALL GETDET(V,W,X)

CALL GETDET( C=X, ELEV=Z )

CALL GETDET(V,W,D=Y)

:

:

SUBROUTINE GETDET ( AREA , DENSIT ,C , D , ELEV )

REAL, OPTIONAL,INTENT(INOUT) :: AREA,DENSIT,C,D,ELEV

:

END

OPTIONAL Arguments and & Keyword Arguments cont..

Page 22: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Always Use INTERFACE to declare External Routines with Optional Arguments

PROGRAM MAIN

INTERFACE

SUBROUTINE SOLVE ( A , B ,C , D , E )

REAL , OPTIONAL, INTENT(INOUT) :: A,B,C,D,E

END SUBROUTINE SOLVE

FUNCTION ZZZ

:

END FUNCTION ZZZ

END INTERFACE

:

CALL SOLVE ( NEWX , E=DELTA_SOFAR )

Page 23: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

USE FUNCTION PRESENT TO CHECK THE PRESENCE OF AN OPTIONAL ARGUMENT

SUBROUTINE SOLVE ( A , B ,C , D , E )

REAL , OPTIONAL, INTENT(INOUT) :: A,B,C,D,E

:

IF ( PRESENT( D) ) THEN

DD = D

ELSE

DD = 0.001

ENDIF

:

END

Page 24: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Result Clause & Recursive Functions

RECURSIVE FUNCTION FACTORIAL ( N ) RESULT (MULT)

INTEGER :: MULT

INTEGER, INTENT(IN) :: N

IF( N = = 1 ) THEN

MULT = 1

ELSE

MULT = N*FACTORIAL( N-1)

ENDIF

RETURN

END

! Note: INTEGER RECURSIVE FUNCTION( ...) is also valid syntax.

Page 25: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Array Valued Functions

FUNCTION NORM( A )

REAL, INTENT=IN :: A

REAL , DIMENSION(SIZE(A) ) :: NORM

REAL : MINI , MAXI

MINI = MINVAL(A)

MAXI = MAXVAL(A)

IF ( MINI - MAXI .LE. 0.0 ) THEN

NORM = 0.0

ELSE

NORM = ( A - MIN) / (MAX-MIN)

RETURN

END FUNCTION NORM

Page 26: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Common Blocks

• Common blocks can be used to make a set of variables available to a selected set of program units without having to use INTERNAL program units.

• Syntax: COMMON /name/ variables_list

EXAMPLE:

REAL :: ARATIO , RATE(10,10)

INTEGER :: TEMP

COMMON /RATIOS/ ARATIO, RATE, TEMP

Page 27: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Common Blocks

• Variables which are declared to be in a COMMON BLOCK can be made available to any program unit by declaring the same set of variables and the common block.

• A common block is a continuous area of memory where the variables are stored in the order of declaration in the COMMON statement, rather than the names. Therefore it is vitally important to keep to the same order in all declarations of the same COMMON BLOCK.

Page 28: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Common Blocks & INCLUDE Files

• To avoid mistakes use INCLUDE files.

• INCLUDE statement is not part of the FORTRAN specifications but all known compilers accept it.

• The statement: INCLUDE ‘filename’ makes the compiler read the contents of the specified file at that point, pretending that it is all part of the source inserted at that point.

Page 29: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Common Blocks & INCLUDE Files

• By putting the declarations for all the variables within a common block and the COMMON statement which follows it into a file and using the INCLUDE ‘filename’ statement in every subroutine or function which uses that common block, we can ensure that there are no problems arising from misspelling or mis-declaration of common block variables.

Page 30: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

INCLUDE: examples

• Create a file called RATIOS.INC which contains the following set of lines.

REAL :: ARATIO , RATE(10,10)

INTEGER :: TEMP

COMMON /RATIOS/ ARATIO, RATE, TEMP

Now in every program unit where you intend to use this common block simply add the line:

INCLUDE ‘RATIOS.INC’

within the declarations section.

Page 31: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

MODULES

• Think of Modules as the next step from the COMMON BLOCKS concept.

The idea of common blocks was to make the same set of variables available to as many different routines as required. Modules take this concept further to make a set of variables ( and optionally subroutines&functions which act on that data) available in a unified manner.

• Modules can also deliver the functionality that INCLUDE statements have provided in the past.

Page 32: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Module ExampleMODULE DECK

INTEGER :: CARD(52) , LASTCARD

CONTAINS

SUBROUTINE DRAWONE( ACARD )

INTEGER ACARD

LASTONE = LASTONE - 1

IF ( LASTONE.LE.0 ) LASTONE = 52

ACARD = CARD(LASTONE)

RETURN

END SUBROUTINE DRAWONE

END MODULE DECK

Page 33: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Module Example continued …

SUBROUTINE DEAL

USE DECK

:

CALL DRAWONE

END

Note: Modules are also useful for containing the INTERFACE definitions.

Page 34: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

USE Statement Syntax ..

SYNTAX: USE module

USE module , renamelistUSE module, ONLY :namelist

where; renamelist is newname=>oldname

This form of usage is needed when there is a chance of a clash of local names with the variable of procedure names in a USEd module.

EXAMPLE:SUBROUTINE DEAL

REAL :: drawone

USE DECK, GETNEXT==> DRAWONE

:

CALL GETNEXT

END

Page 35: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

USE statement continued..

ONLY Clause is useful when only a sub-set of names defined in a module is to be used and the others remained invisible.

Example:

MODULE PHY_CONSTANTS

REAL :: G = 9.81

REAL :: PLANK = 6.624E-27

REAL :: C = 2.99796E8

END MODULE PHY_CONSTANTS

SUBROUTINE CALC

:

USE PHY_CONSTANTS, ONLY : G

Page 36: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Operator Overloading

• Operator overloading means extending the definition of intrinsic operators when they are applied to user-defined-types.

For example:*,+,-,/ are intrinsic operators and their effect when applied to intrinsic types ( ie REAL,INTEGER etc.) are clear ( and can not be changed ).

But we have the freedom to define the meaning of *,/,+ etc. when we apply them

to user defined types.

Page 37: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

operator overloading cont...

EXAMPLE: MODULE CHAR_FEATURES : INTERFACE OPERATOR(+) MODULE PROCEDURE joinup END INTERFACE : CONTAINS FUNCTION joinup( str1,str2) CHARACTER*(*) , INTENT(IN) :: str1 , str2 CHARACTER(LEN=LEN_TRIM(str1)+LEN_TRIM(str2):: joinup joinup = TRIM(str1)//TRIM(str2) END FUNCTION joinupEND MODULE CHAR_FEATURESWe can now write astring = bstring+cstring

Page 38: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

operator overloading cont...

• We can also define completely new operations and apply them to all ( intrinsic and user-defined ) types:

• A user defined operator have the syntax:

.name.

for example .sum. , .invert.

Page 39: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Defining a New Operator

MODULE GEOM TYPE POINT REAL :: X,Y END TYPE POINT INTERFACE OPERATOR ( .DIST. ) MODULE PROCEDURE CALCDIST END INTERFACE CONTAINS

REAL FUNCTION CALCDIS( P1,P2) TYPE(POINT),INTENT(IN) :: P1 , P2

CALCDIS = SQRT((P1%X-P2%X)**2+(P1%Y-P2%Y)& **2 )

END FUNCTION CALCDIST

END MODULE GEOM

Page 40: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Defining operators continued...

We can now use this module in a program to calculates the distance between points.

program main

use geom

type(point) :: vertex(100) , origin

real :: distance(100) , odist

:

odist (i) = vertex(i).dist.origin

distance(i) = vertex(j) .dist. vertex(k)

Page 41: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

More about Pointers

INTEGER, POINTER :: IVAR , JVAR

REAL, DIMENSION(:), POINTER:: RVEC

REAL, DIMENSION(:,:),POINTER :: RMATRX

• Pointers can point to existing variables

or

• They can be given fresh storage

Page 42: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Pointing To Existing Variables

REAL ,POINTER :: P1 , P2

REAL ,TARGET :: T1 = 1.0 , T2 = 2.0

P1 => T1 ; P2 => T2

P2 = P1 ! an ordinary assignment.copy contents of

! p2 into the location pointed by p2.

P2 => P1 ! a pointer assignment

!

! p1 t1

! p2 1.0

Page 43: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Pointer Assignmentarray pointers

REAL,DIMENSION(:),POINTER :: P

REAL,TARGET :: T(0:9)

REAL :: X(10) , Y(5)

P => T ; X=P ! x(1:10) is set to t(0:9)

P => T(:) ; X(1)=P(1) ! x(1) will be set to t(0)

P => T(0:8:2) ; Y=P ! y(1)=t(0),y(2)=t(2) ...so on

Pointers can be used just like variables in expressions.

e.g. Y = 0.5*sin(P)

Page 44: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Pointer Status

• UNDEFINED - as at start of the program

• NULL – Exists but not associated with anything yet.

• ASSOCIATED – It is associated with a target: points to something!

REAL,POINTER :: P

REAL,TARGET :: T ,U ,V

NULLIFY(P)

P => T

PRINT * , ASSOCIATED(P ) ! .TRUE.

P => U ! We decides to point P to U from now on.

Page 45: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Allocating Memory To Pointers

REAL POINTER , DIMENSION(:,:) :: WORK

:

N = 111

ALLOCATE ( WORK(N,N) )

: !use (work) as an array pointer.

DEALLOCATE( WORK )

RETURN

END

Note: When a pointer is declared so as to access an array, only the shape of the array it will point to should be specified by the DIMENSION statement.

Page 46: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Pointer Arguments

INTERFACE

SUBROUTINE sub1 (B )

REAL DIMENSION(:,:) :: B

END SUBROUTINE sub1

SUBROUTINE sub2( B )

REAL,DIMENSION(: , :),POINTER :: B

END SUBROUTINE sub2

END INTERFACE

REAL DIMENSION(:,:) :: AMATRX

REAL DIMENSION(:,:) , POINTER :: WORK

ALLOCATE( WORK(20,40) )

ALLOCATE ( AMATRX(20,30)

CALL SUB1(AMATRX) ! No pointers involved or needed (usually the case)

CALL SUB1(WORK) ! in sub1 work is an array.

CALL SUB2(WORK) ! in sub2 a pointer to an array.

Page 47: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Input/Output

Data can be read into the program by means of the READ statement, the simplest syntax of which is:

READ( unit , format ) list

Where; unit is either UNIT= n or n , n being an integer representing the input channel number and format is FMT=format_label or a character string/variable and list is the list of variables to read into.

Similarly data output from a program is achieved by means of the WRITE or PRINT statements the simplest syntax of which is:

WRITE(unit,format,) list

PRINT format , list

Page 48: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Input/Output

• READ and WRITE examples:

READ(*,*) N

READ( 5,* ) N

READ(UNIT=5,100) N

100 FORMAT( I8 )

READ(UNIT=5,FMT=110) A

110 FORMAT( F12.4 )

Substituting WRITE for READ in the above statements will yield a valid WRITE statements with the data flowing in the opposite direction.

Page 49: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Examining the I/O units

Write(*, …. )

Fortran program

Read(*, … ) or Print …

A Fortran program will always have default connections to the standard input and standard output. In the case of an interactive job this will be Screen and Keyboard as shown here. • * Will always imply default i/o. Different compilers associate different unit ‘channel’ numbers with default i/o devices. Usually 5 => keyboard , 6=>display •Therefore ( READ(5, … means READ(*, … ) and WRITE(6,.. ) means WRITE(*,…)

Page 50: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Reading from a file

Fortran program

Data.filOpen( Unit=12,File=‘data.fil’,action=‘read’)

READ(12, … )

READ(12, … )

READ(12, … )

CLOSE( UNIT=12 )

REWIND( UNIT=12 )

Page 51: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Writing to a file

Fortran program

output.filOpen( Unit=12,File=‘output.fil’,action=‘WRITE’)

WRITE(12, … )

WRITE(12, … )

WRITE(12, … )

CLOSE( UNIT=12 )

Page 52: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Examining the I/O units

Fortran Program

Input File

Output F

ile

Read / Write File

Page 53: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … unit specifier

A unit specifier is a positive integer number that allows us to form an association between a file and our program.

It can be thought of as communications channel number.

Portability tips : Avoid using 0, 1, 2, 5 and 6 as unit numbers when opening files as may be associated witht the default input/output channels.

Safe to use 10 and higher.

Avoid numbers beyond 128 as well !

Unit= may be omitted if it is the first token.

Example :

OPEN(UNIT=15,FILE=‘MYDATA’ ) is the same as …

OPEN(15,FILE=‘MYDATA’ )

Page 54: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … FILE specifier …

Along with the UNIT specifier, FILE specifier is the most important element of the OPEN statement.

It can be a character constant or a character variable.

For example:

CHARACTER*32 FNAME=‘mydata.fil’

OPEN(UNIT=16,FILE=FNAME )

Is the same as

OPEN(UNIT=16,FILE=‘mydata.fil’ )

If a filename is not fully qualified it is assumed to be in the current working directory. Alternatively filenames can be fully qualified

For example; OPEN(UNIT=17,FILE=‘/scratch/cs4un5/tmp/sample.dat’ )

Page 55: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … Status of files

STATUS flag is very useful and more intuative to use.

STATUS= ‘OLD’ File must be an existing file.

STATUS=‘NEW’ File must not exist.

STATUS=‘SCRATCH’ File will be deleted at the end of the execution.

STATUS=‘UNKNOWN’ Most forgiven form.

STATUS=‘REPLACE’ . Create if does not exist, Overwrite if it does.

PIT FALL WARNING: When using STATUS=‘NEW’ a program may work the first time it is run and fail to work in subsequent runs.

Page 56: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … ACTION specifier

The ACTION specifier can be used to clarify your intent about the read/write access required to a particular file when it is OPENed.

ACTION=‘READ’

ACTION=‘WRITE’

ACTION=‘READWRITE’

When READ is specified WRITE to that file will fail.

When WRITE is specified READ from that file will fail.

READWRITE will put no restrictions but beware of danger of deleting contents of existing files unintentionally.

Page 57: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … Position Specifiers

If no position is specied the file-pointer points to the beginning ( the first record ) of a file.

Therefore this specifier is only needed if appending to an existing file is desired.

POSITION= ‘APPEND’

Page 58: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

OPEN … Error handling related

The specifiers IOSTAT= , END= and ERR= are all useful for trapping unexpected errors during file handling and taking the necessary actions, even if it is just to put out a message and terminate the program.

All good programs should make use of one or more of these.

Without these specifiers, if an error occurs during an OPEN statement the program will terminate immediately.

For example trying to open a non-existing files with STATUS=‘OLD’ or trying to open a file with only READ access by using ACTION=‘WRITE’ are two such possible causes of errors.

If IOSTAT=integer_var is used in an OPEN statement then errors during that OPEN will not cause a termination but the integer variable specified by IOSTAT will be given a non-zero value to indicate that an error occured.

If there were no errors IOSTAT will return 0.

It is therefore essential to have test statement of the form as follows

OPEN(UNIT=NUMU,FILE=FILNAME,IOSTAT=IWHAT)

IF( IWHAT .NE. 0 ) THEN ! Do error handling …

Page 59: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Error handling from READ/WRITE statements

ERR= specifier is particularly useful with the READ statements when formatting errors may result in a misread.

END=specifier is also very useful in combination with the READ statement particularly when reading files of unknown length.

IOSTAT values returned by READ,WRITE, OPEN, CLOSE, REWIND, BACKSPACE, INQUIRE statements: These are not defined by standards. Every compiler has documented list of IOSTAT values and what they mean. 0 always means it is OK.

Page 60: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

READ statement with the END specifier

K= 0

DO

READ( 15,*, END=20 )

K = K + 1

:

ENDDO

20 NUM_OF_RECORDS = K

:

If the end of the file is reached when attempting to READ, execution will jump to the statement labeled 20.

Page 61: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

READ statement with the ERR specifier

40 Write(‘ Your passcode must be a whole integer number’ )

:

Write(*,(‘ENTER YOUR PASSCODE:’ )

READ(* , ’(I10) ’ , ERR = 40 ) ICODE

:

Here, user typing a real number or any non-numeric characters will cause an error condition. In that situation, without the ERR= clause this program would terminate. However, with the ERR= clause the program will continue executing from the statement label referred by the ERR clause.

Page 62: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Input/Output using read/write

FORMATTED, READ or WRITE:READ(UNIT=u, FMT=fmt, IOSTAT=ios, ERR=er_lab, END=end_lab, ADVANCE=string ) list

WRITE( … same as above …) variables_list

UNFORMATTED, READ or WRITE:READ(UNIT=u, IOSTAT=ios, ERR=er_lab, END=end_lab,ADVANCE=string ) list

WRITE( … same as above …) variables_list

DIRECT, READ or WRITE:

READ(UNIT=u, REC=n, IOSTAT=ios, ERR=er_lab, END=end_lab ) list

WRITE( … same as above… ) list

KEYWORDS: UNIT=unit_number,FMT=format_label or CHARACTER VARIABLE/STRING)

IOSTAT=integer_variable, ERR=label_id. END=label_id

REC=record_number (INTEGER )

ADVANCE=‘YES’ or ‘NO’

Page 63: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Close Statement

When you finished processing files opened using the OPEN statement you may close them “and hence detach them from your program” by using the CLOSE statement.

Syntax:

CLOSE ( UNIT=u, IOSTAT=ios,ERR=label,STATUS=‘status’)

All except unit is optional. I.e. CLOSE(24) is perfectly acceptable.

IOSTAT and ERR are as described earlier.

STATUS is a character variable or string with the value ‘KEEP’ or ‘DELETE’ that requires the action to take upon closing.

Notes:

- All files are closed automatically when a program terminates.

- You can use the same unit number again and again to open another file once you closed a unit.

Page 64: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Rewind and Backspace Statements

Rewind the file back to the beginning. I.e. move the file pointer to the beginning of the file.

REWIND unit_no

REWIND ( UNIT= unit_no , IOSTAT= IOS , ERR= label)

Go back to the last record read ( so as to be able to re-read it )

Or the last record written ( so as to over-write it with a new one)

BACKSPACE unit_no

BACKSPACE( UNIT= unit_no , IOSTAT=IOS , ERR=label )

Not applicable to direct access files

Page 65: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

INQUIRE statement

Check the status of a file;

Examples;

INQUIRE(file=filename , EXIST=logical_var )

Can take also the following parameters;

IOSTAT= , NUMBER= , NAMED= ACCESS= , FORM=

RECL= , NEXTREC= , POSITION= , ACTION= , READ= WRITE=, READWRITE=

Page 66: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Internal I/O

The normal I/O is to the external (files) from READ and WRITE statements, such as ;

READ(unit_specifier , format_specifier )

WRITE(unit_specifier , format_specifier )

Where unit_specifier is UNIT=integer_var or simply integer_var.

However, with internal I/O instead of the unit_specifier a CHARACTER VARIABLE is used. The effect of this is to write the output to ( or read from ) the character variable instead of sending it to a file.

Page 67: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Internal I/O

Example:

CHARACTER*128 LINE

CHARACTER*20 :: NAME=‘Deniz Savas’

CHARACTER*10 :: DEPT =‘CITI’

INTEGER :: TEL_NO=23023

INTEGER :: ROOM_NO=101

WRITE(LINE,100) DEPT, ROOM_NO, NAME,DEPT

100 FORMAT( A10 , I6 , A20 , I4 )

! From now on LINE contains: ‘CITI … 101 ..Deniz … ‘

Page 68: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Format Specifications

Format specifications are used in READ and WRITE statements.

F, E,D,G, P : Used for floating-point numbers

I : Used for Integers

A : Used for character strings

L : Used for Logical Variables

T , TL,TR : specify position from left , from-right

X, ’any_char_string’ , /

Page 69: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Format Specification Examples

INTEGER :: IYEAR, IMONTH , IDAY

REAL :: AMARK

CHARACTER*12 :: ANAME , AFORM

READ( IU , 100 ) IYEAR,ANAME,AMARK

100 FORMAT(I8,2X,A12,5X,F12.4)

AFORM=‘(2X,3(I6,1X) )’

READ( IU, FMT=AFORM ) IYEAR,IMONTH,IDAY

WRITE(IO,120) ANAME , AMARK , IDAY

120 FORMAT( 5X,A,4X,G12.4 ,’ ON DAY NO: ‘, I8 )

Page 70: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

File Handling Examples

Examples:

CHARACTER*36 FILNAM

INTEGER K

OPEN (UNIT = 10 , FILE= ‘DATA.FIL’)

OPEN(UNIT =11, FILE=‘TEST.TXT’,STATUS=‘OLD’ )

OPEN(UNIT=K ,FILE=FILNAM , STATUS=‘NEW’)

CLOSE(UNIT=11)

CLOSE(UNIT=12,STATUS=‘DELETE’)

Page 71: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

Acknowledgement &References:

• Thanks to Manchester and North High Performance Computing, Training & Education Centre for the Student Notes.

• See APPENDIX A of the above notes for a list of useful reference books

• Fortran 90 for Scientists and Engineers, Brian D Hahn, ISBN 0-340-60034-9

• Fortran 90 Explained by Metcalf & Reid is available from Blackwells ‘ St Georges Lib.’

Oxford Science Publications, ISBN 0-19-853772-7

Page 72: Introduction to  Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University

THE END