introduction to fortran95 programming part iii by deniz savas, citi, clemson university

Post on 30-Dec-2015

43 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Introduction to Fortran95 Programming Part III By Deniz Savas, CITI, Clemson University dsavas@clemson.edu. 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

TRANSCRIPT

Introduction to

Fortran95 Programming

Part III

By Deniz Savas, CITI, Clemson University

dsavas@clemson.edu

Summary of Part 3

• Program Units:

Subroutines

Functions

Modules

Common Blocks

Include Statements

• More on Pointers

• Input/Output and File Handling

Program Units

• Main Program

• External Procedures− Subroutines

− Functions

• Internal Procedures − Subroutines

− Functions

• Modules

• Common Blocks

Program Structure

[PROGRAM [program_name] ]

[ Data specification & declaration_statements]

[executable_statements]

[contains]

[internal_procedures]

END [ PROGRAM [program_name]

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.

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.

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.

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

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

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

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

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 )

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.

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.

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!

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

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.

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

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

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.

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..

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 )

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

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.

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

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

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.

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.

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.

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.

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.

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

Module Example continued …

SUBROUTINE DEAL

USE DECK

:

CALL DRAWONE

END

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

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

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

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.

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

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.

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

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)

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

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

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)

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.

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.

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.

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

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.

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(*,…)

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 )

Writing to a file

Fortran program

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

WRITE(12, … )

WRITE(12, … )

WRITE(12, … )

CLOSE( UNIT=12 )

Examining the I/O units

Fortran Program

Input File

Output F

ile

Read / Write File

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’ )

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’ )

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.

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.

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’

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 …

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.

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.

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.

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’

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.

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

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=

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.

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 … ‘

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’ , /

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 )

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’)

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

THE END

top related