



Format Specifications or WRITE statement which uses a formatted external file or an internal
file must include a format identifier. This may have any of the following
forms:
FMT=* FMT=label FMT=char-exp FMT=char-array FMT= may be omitted if it is the second item in
the I/O control list and if the unit identifier with UNIT= omitted comes
first.
A format specification consists a pair of parentheses enclosing a list of items called edit descriptors. Any blanks before the left parenthesis will be ignored and (except in a FORMAT statement) all characters after the matching right parenthesis are ignored.
In most cases the format can be chosen when the program is written and the
simplest option is to use a character constant:
WRITE(UNIT=LP, FMT='(1X,A,F10.5)') 'Frequency =', HERTZ
Alternatively you can use a FORMAT statement:
WRITE(UNIT=LP, FMT=915) 'Frequency =', HERTZ 915 FORMAT(1X, A, F10.5) |
FORMAT statement may also be the neater form if the specification is long and
complicated, or if character-constant descriptors are involved, since the enclosing
apostrophes have to be doubled up if the whole format is part of another character
constant.
It is also possible to compute a format specification at run-time by using a suitable character expression. By this means you could, for example, arrange to read the format specification of a data file from the first record of the file. The program fragment below shows how to output a real number in fixed-point format (F10.2) when it is small, changing to exponential format (E18.6) when it is larger. A threshold of a million has been chosen here.
CHARACTER F1*(*), F2*12, F3*(*) *Items F1, F2, F3 hold the three parts of a format specification. *F1 and F3 are constants, F2 is a variable. PARAMETER (F1 = '(1X,''Peak size ='',') PARAMETER (F3 = ')') *... calculation of PEAK assumed to be in here IF(PEAK .LT. 1.0E6) THEN F2 = 'F10.2' ELSE F2 = 'E18.6' END IF WRITE(UNIT=*, FMT=F1//F2//F3) PEAK |
'Peak size =' have
been doubled in the PARAMETER statement because they are inside another character
constant. Here are two examples of output records, with blanks shown explicitly:
Peak |
The FORMAT statement is classed as non-executable and can, in principle, go
almost anywhere in the program unit. A FORMAT statement can, of course, be
continued so its maximum length is 20 lines. The same FORMAT statement can be used
by more than one data transfer statement and, unless it contains character
constant descriptors, used for both input and output. Since it is very easy to
make a mistake in matching the items in a data transfer list with the edit
descriptors in the format specification, it makes sense to put the FORMAT
statement as close as possible to the READ and WRITE statements which use
it.