Input/output operations (i.e., reading/writing data) are avery important part of computer programming. This chapter describes basic input/output operations, beginning with the READ and WRITE statements. The READ statement is an input statement; the WRITE statement is an output statement. The OPEN statement is used to open a file for reading or writing purposes. The CLOSE statement reverses the action of the OPEN state ment. The DATA statement is used to provide initial val ues for variables, or in place of input data. There are two types of input/output operations: (1) unformatted, which do not follow a specific way of reading or writing, and (2) formatted, which follow a specific way. Unformatted input/output is much simpler than for matted. The emphasis of this chapter is on unformatted input/output. Chapter 6 describes formatted input/output in more detail. 2.1 RECORDS AND FILES
A record is the basic unit of input/output operations. A
record is a sequence of characters constituting one value, or a
sequence of values forming one line. For instance, a line on a
computer or terminal screen is usually considered to be a
record. When entering data, pressing the carriage RETURN key
signals the end of a record. In other words, the RETURN key is
a record separator. Records are of two types: (1) unformatted, and (2)
formatted. Unformatted records do not follow a format
specification and they may be read or written only by unformatted input/output statements.
Formatted records follow a
format specification and they may be read or written only by
formatted input/output statements.
A file is a sequence of records forming an entity which can
be addressed by the operating system. Files can be either
external or internal. An external file is any file that exists
independently of the executable program. An internal file is
used for the purpose of transferring data from one location in
(internal) storage to another location in (internal) storage.
Input statements transfer data from external media (an
external file or the screen) or an internal file to internal
storage. This process is called reading, and it is accomplished with the READ statement. Output statements transfer data from internal storage to
external media (an external file or the screen) or an internal
file. This process is called writing and it is accomplished
with the WRITE (or PRINT) statement.
Format specification is accomplished with a FORMAT
statement. A programmer choosing unformatted input/ output does
not need to specify FORMAT statements. In this case, the
processor controls how input data is read and how output data
is written.
A programmer choosing formatted input/output must use FORMAT
statements to read and/or write data. In this case, the
programmer retains control on how input data is read and how
output data is written.
As a general rule, it is good programming practice to use
unformatted records for input (reading) operations, and
formatted records for output (writing) operations. Unformatted
input frees the programmer or user from having to count columns
and blank spaces on a data record. Formatted output has the
advantage that it can be made to look exactly as desired.
Example: Unformatted and Formatted Input/Output 2.2 UNITS AND FILE CONNECTION
Processors use certain numbers called logical units to con
nect to a file for input/output operations. Logical units can
vary from 1 to 100, allowing the simultaneous connection of up
to 100 files. The numbers 5 and 6 are the usual default
logical units for interactive screen input and output,
respectively. Other numbers in the range 1-100 can be arbitrarily chosen to connect to files.
The OPEN statement is used to connect a file to a unit. The
CLOSE statement is used to disconnect a file from a unit. A
file must not be connected to more than one unit at the same
time. A unit must not be connected to more than one file at the
same time.
Input data can either
If the input data resides in an input file, the latter can be read every time the program is executed. If the input data does not reside in an input file, the data has to be entered anew every time the program is executed. In general, a long input data stream (consisting of a large number of records, say, more than 10) should reside in an input file. On the other hand, a short input stream (say, a few records) may be entered directly to the screen every time the program is executed. Output data can either
If the output data is written to an output file, it is effectively stored and can be referenced as many times as desired, until such time when it is no longer needed and can be deleted--i.e., erased from disk storage. If the output data is displayed directly on the screen, it is available for immediate examination, but it is not stored. In general, a long output stream should be written to an output file, for immediate examination or long-term storage. On the other hand, a short output stream may be displayed directly on the screen, for immediate examination only. The direct screen input/output mode is often referred to as interactive mode. Typically, in the absence of a specific instruction to the contrary, a processor will regard the interactive mode as the default input/output mode. The numbers 5 and 6 are the usual default logical units for interactive screen input and output, respectively. Throughout this book, the units 5 and 6 will be taken in this context.
2.3 READ STATEMENT
The READ statement is the data transfer input statement. It has the typical form: READ(UNIT=5,FMT=12) A,B,C Note that the READ statement keyword is followed by UNIT= 5 and FMT= 12, enclosed within parentheses, and separated by a comma. This statement will read the vari ables A, B, and C from the file that is connected to unit 5 following the format marked with the statement label 12. If interactive read is connected to unit 5 (the usual default setting), the input data is entered directly to the screen during program execution. The above statement can also be written as: READ(5,12) A,B,C where the optional characters UNIT= and FMT= have been omitted for simplicity. If these characters are omitted, the following rules should be adhered to:
The form READ(*,12) A,B,C will read variables A, B, and C using direct screen input and following the format with statement label 12. The * in place of the unit specifier stands for direct screen input, i.e., interactive input. The form READ(5,*) A,B,C will read variables A, B, and C from the file connected to unit 5 and use unformatted input. The * in place of the format label stands for unformatted input. An unformatted READ is also referred to as a list-directed READ. The form READ(7,*) A,B,C will connect an input file to unit 7 and use unformatted in put. Since unit 7 is not normally used for interactive input, the connection to unit 7 is accomplished with an OPEN statement (see Section 2.5). The unit specifier does not need to be a constant. The form READ(LU,*) A,B,C will connect to a variable logical unit LU and use unformatted input. The value of LU should be defined in the source program prior to the execution of this READ statement. The READ statement has other specifiers, besides the unit and format specifiers. The form READ(7,15,ERR=80,END=90) A,B,C will read variables A, B, and C from the file connected to unit 7, following format labeled 15. In addition:
The indicated statement labels (80 and 90) must exist elsewhere in the program unit. Either ERR or END or both may be specified in a READ statement. The characters ERR= and END= preceding the label specifiers are required and cannot be omitted. 2.4 WRITE STATEMENT
The WRITE statement is the data transfer output state ment. Unlike the PRINT statement, which is permanently connected to direct screen output, the WRITE statement may also be used to write to a file. Therefore, the WRITE statament has more flexibility, and is preferred by most programmers. The WRITE statement has the typical form: WRITE(UNIT=6,FMT=15) X,Y,Z This statement will write the variables X, Y, and Z to the file connected to unit 6 following the format labeled 15. When unit 6 is connected to interactive write (default value), the output data is displayed directly on the screen during program execution. The above statement can also be written as: WRITE(6,15) X,Y,Z where the optional characters UNIT= and FMT= have been omitted for simplicity. In this case, the same rules as for the READ statement apply. The form WRITE(*,15) X,Y,Z will write variables X, Y, and Z using direct screen output and following the format labeled 15. The * in place of the unit specifier stands for direct screen output (interactive output). The form WRITE(6,*) X,Y,Z will write variables X, Y, and Z to the file connected to unit 6 and use unformatted output. The * in place of the format label stands for unformatted output. An unformatted WRITE is also referred to as a list-directed WRITE. The form WRITE(8,15) X,Y,Z will connect to unit 8 and follow format 15. Since unit 8 is not normally used for interactive output, the connection to unit 8 is accomplished with an OPEN statement (see Section 2.5). The unit specifier does not need to be a constant. The form WRITE(LU,25) X,Y,Z will connect to unit LU and follow format 25. The value of LU should be defined in the source program prior to the execution of this WRITE statement. The form WRITE(9,40,ERR=90) X,Y,Z will write variables X, Y, and Z to the file connected to unit 9 following format labeled 40. An error condition during output operation will branch control to statement labeled 90. The indicated statement label (90) must exist elsewhere in the program unit. Algebraic expressions can also be listed in a WRITE statement, as shown in the following example: WRITE(6,20) 2*A,3.5*B In this case, the first value written is equal to twice the value of A; the second is equal to 3.5 times B. Example Program: READ and WRITE Statements
In the above program, the variables A, B, and C are read directly into the screen (unit 5 specifier), the indicated operations are performed, and the results are printed directly onto the screen (unit 6 specifier). Assuming A = 10.8, B = 7.8, and C = 3.2, the output would look like this: X IS EQUAL TO 18.6000 Note that if an error is encountered while reading C, the output would simply look like this: ERROR WHILE READING C 2.5 UNFORMATTED INPUT/OUTPUT RULES
The following rules are for unformatted input/output:
An input value or values should have no embedded blank
spaces (i.e., blanks in the middle), and should be separated
among themselves either by:
Character constants should be enclosed by apostrophes and separated among themselves in the same way as other values.
During input, the processor is directed to read as many values as variables are listed in the READ statement. This is why unformatted input is also referred to as list- directed READ.
During output, values are written with spacing and char acteristics remaining under the control of the processor.
2.6 OPEN STATEMENT
The OPEN statement initiates a connection between an external file and a specified unit. It has the typical form: OPEN(UNIT=5,FILE='A.DAT',STATUS='UNKNOWN') This statement will connect the external file A.DAT (an input data file) to unit 5. The character UNIT= is optional only if the unit specifier (5) is the first item on the list enclosed in parenthesis in the OPEN statement. In this case, the previous statement reduces to: OPEN(5,FILE='A.DAT',STATUS='UNKNOWN') The status specifier can be OLD, NEW, SCRATCH, REPLACE, or UNKNOWN. For some compilers, the status specifier may be optional.
The file name specification can be omitted, as shown in the following example: OPEN(7,STATUS='UNKNOWN') In this case, a default file name which is processor depend ent (e.g., FOR007.DAT) is connected to unit 7. Another option is to include an error specifier in the OPEN statement, as in the following example: OPEN(7,STATUS='UNKNOWN',ERR=97) If an error is encountered during the execution of this OPEN statement, control branches to the statement labeled 97. Example: OPEN statement
This example connects file P.DAT to unit 5, file P.OUT to unit 6, file Q.DAT to unit 7, and file Q.OUT to unit 8. It reads from P.DAT at least one (and at most three) record(s) containing values of variables A, B, and C. It writes to P.OUT the values A, B, and C. It reads from Q.DAT at least one (and at most two) record(s) containing values of variables D and E. It writes to Q.OUT the values D and E. Note that each OPEN statement physically precedes its respective READ or WRITE statement. 2.7 CLOSE STATEMENT
The CLOSE statement disconnects an external file from a specified unit; therefore, it reverses the action of the OPEN statement. After a unit has been disconnected from a file by the execution of a CLOSE statement, either may be connected again within the same executable program, either to the same unit or file or to another unit or file. The CLOSE statement takes the form: CLOSE(UNIT=5,STATUS='KEEP') This statement disconnects unit 5 from a file name and keeps (i.e., saves) the file. The status specifier can be KEEP or DELETE.
The character UNIT= is optional if the unit specifier is the first item on the list enclosed in parenthesis in the CLOSE statement. In this case, the previous statement simplifies to: CLOSE(5,STATUS='KEEP') The form CLOSE(5) will disconnect unit 5 from a file name and keep the file (unless the file status is SCRATCH, see above). If desired, an error specifier may be included in the CLOSE statement. For instance, in CLOSE(5,ERR=98) an error condition encountered during the execution of this CLOSE statement will branch control to the statement labeled 98. At termination of program execution (for reasons other than an error condition), all connected units are automati cally closed. Therefore, it is usually not necessary to explicitly close units at the end of a source program. 2.8 DATA STATEMENT
The DATA statement is used to provide initial values for
variables. It takes the typical form: DATA A,B,C /12.,23.4,-45./
This statement assigns to variables A, B, and C the initial
values 12., 23.4, and -45., respectively. The slashes (/) de
limiting (enclosing) the values are required, as well as the
commas used to separate them. The number of values en
compassed within the slashes (/) must equal the number of
variables immediately following the keyword DATA.
Another way to write a DATA statement is the following:
DATA A,B,C /3*10./
All three variables A, B, and C have been initialized with
the value 10. using a repeat factor (3 in this case). The
repeat factor must be a positive integer. The above statement
is equivalent to:
DATA A,B,C /10., 10., 10./
DATA statements are used: to assign initial values to variables whose values will
be later modified during program execution, or
to assign the proper values to constants that will not
vary from one program application to the next. DATA statements can be interspersed among executable
statements (see Figure 1.1). However, it is good pro gramming
practice, for easy reference, to place all DATA statements
together, immediately preceding the executable portion of the
source program or subprogram. Make sure that the number of variables matches
the number of assigned values. Be sure to include two slashes (/), one preceding and another following the listed values. Be sure to separate the variables and values with
commas. If you use a repeat factor, confirm that it is
a positive integer, and that the number of values (including
those repeated with a repeat factor) matches the number of
variables. For easy reference, consider placing all DATA
statements together, preferably immediately preceding the
executable statements. 2.9 DEBUGGING TOOLS
This section introduces the programmer to debugging and
debugging tools. This section should be used as a continu ing
reference. However, effective debugging is learned by
compiling and running many programs successfully. Al though
initially a slow process, debugging skills improve with
practice.
All Fortran programs need to be debugged before they can be
used effectively. Debugging refers to the process of re moving
errors, whatever their source. Success in programming depends
on how fast and how thoroughly the pro grammer is able to
identify and correct errors that may arise in the course of
normal program development. Debugging is both an art and a
science, and experience is essential to success. However,
thorugh a careful study of the nature of these errors, and of
the strategies to correct them, the programmer can acquire the
tools and develop the confidence to effectively debug Fortran
programs. Errors in Fortran program development and execution can be
categorized into four classes: Class I: Errors in statement spelling and/or syntax. Class II: Errors in compatibility in input/output opera
tions. Class III: Errors in logic and compatibility within and
between program units. Class IV: Errors in input values.
Class I errors are common during the early stages of
program development, and are relatively easy to debug. During
compilation, Fortran compilers generate a list file which is
available to the user upon demand. A list file has the same
name as the Fortran file, but a different file extension. For
example, the list file for MYPROG.FOR is MYPROG.LIS.
(MYPROG.LST for some compilers). The list file lists the source program and flags the
line(s) which contain spelling or syntax errors, e.g., a
missing closing parenthesis. Usually, the error is to be found
within the flagged line, but sometimes, it is found in the
line immediately preceding or following. Careful examination
of the flagged lines and their immediate vicinity should take
care of most if not all Class I errors.
Class II errors are a little harder to debug than
Class I errors. In formatted input/output (Chapter 6), the
processor is extremely unforgiving, and will not tolerate
incompatibilities between READ/WRITE and FORMAT state ments.
For instance, the most common Class II error results from an
attempt to read a real variable using an integer format, or
viceversa. Fortunately, Class II errors produce runtime error
messages which generally point the programmer in the right
direction as far as error diagnosis is concerned. In
unformatted input/output, the processor is more forgiving, but
the drawback here is that some errors may go undetected.
Class III errors are more difficult to debug than
either Class I or Class II errors. A Class III error could be
one of logic or compatibility. During runtime, the processor
will usually flag a Class III logic error, helping the user to
di agnose it. A typical example of a Class III logic error is
an attempt to divide by zero. The best way to debug this type
of error is to identify the problem line and the source of the
error, and to fix it. The WRITE statement and the D_LINES
Fortran command qualifier (see Section 1.1) should be used
freely to help identify the problem line. Unlike a Class III logic error, the processor will usually
not flag a Class III compatibility error. In other words, a
program could be compiled, linked, and run, apparently
successfully, with the processor being unable to discern and
flag a Class III compatibility error.
An example of this type of error is that associated with
the im proper addressing of storage locations, e.g., errors in
subprogram argument lists or in COMMON statements. The best
way to debug a Class III compatibility error is to test the
program against a "benchmark," i.e., a problem for
which the solution is known beforehand. The user should also
ask himself is the result is reasonable. If the answer to this
question is NO, a compatibility error may be at work. While
short programs (say, up to 100 source lines) can be readily
tested for Class III compatibility errors, long programs may
not. This is why long programs should be segmented into
subprograms (Chapter 9), and the subprograms tested
separately.
Class IV errors could be the most difficult to
detect, because no help can be expected to come from the
proces sor. This type of error occurs when a value entered
into storage is, due to an oversight, not what it was
intended. For example, assume a variable has a value of 3.92.
By mistake, the value is entered as 3.29. This type of error
can only be corrected through careful scrutiny of the input
file. 2.10 EXAMPLE PROGRAMS
Example Program 1: Use of DATA Statement and Connection to
an Output File (for later printing) The following program uses
a DATA statement to assign specific values (3. and 4.) to the
two sides of a right trian gle. Then it proceeds to calculate
the hypotenuse using the intrinsic function SQRT(X) and to
write all three values to an output file named SIDE_C.OUT. (An
intrinsic function is a commonly used function that is
supplied as part of the FORTRAN library. For a list, refer to
Section 5.4). Note that this is only an example. Normally,
input would not be performed with a DATA statement, but
rather, via an input file (Example 2) or directly to the
screen (Example 3).
The optional PROGRAM statement is at the top; the END
statement is at the bottom. The DATA statement precedes all
executable statements for the sake of improved readability.
The OPEN statement connects unit 6 to file SIDE_C.OUT and
precedes all WRITE statements. All WRITE statements are
unformatted. Using operating system commands, the output file
(SIDE_C.OUT) can be examined by editing it, typing it (to the
screen), or printing it (obtaining a hard copy). Example Program 1: Data Statement And Output File Example Program 2: Connection to Input and Output
Files
The following program reads the values of the two sides of
a right triangle from an input file SIDES.DAT. It proceeds to
calculate the hypotenuse using the intrinsic function SQRT(X)
and to write the value of the hypotenuse to an output file
SIDE_C.OUT. Note the order of statements in this program. The PROGRAM
statement is at the top. The END statement is at the bottom.
An OPEN statement connects unit 5 to input file SIDES.DAT and
precedes the READ statement. An other OPEN statement connects
unit 6 to output file SIDE_C.OUT and precedes the WRITE statement. Both READ and
WRITE statements are unformatted. There is no need for STOP or
CLOSE statements in this example.
Using an editor, the input file (SIDES.DAT) should be
created before running this program. Otherwise, the vari ables
SIDEA and SIDEB would be undefined at running time. After
running the program, the generated output file (SIDE_C.OUT)
can be examined by editing it, typing it (to the screen), or
printing it (obtaining a hard copy).
Example Program 2: Connection to Input and Output
Files
Example Program 3: Direct Screen Input and Output The following program reads the values of the two sides of
a right triangle directly from the screen (direct screen or
interactive input). It proceeds to calculate the hypotenuse
using the intrinsic function SQRT(X) and to write the value of
the hypotenuse directly to the screen (direct screen or
interactive output). Note the following features of this program:
The PROGRAM statement is at the top; the END state ment
is at the bottom.
Each of the two READ statements is immediately pre
ceded by a WRITE statement containing an input prompt, which
is a character constant displayed on the screen to prompt the
user to enter the requested input data.
This program generates its own input prompts by means
of an unformatted WRITE. Example Program 3: Direct Screen Input and Output
Example Program 4: Direct Screen Input with Formatted Input Prompts The only difference between this example and the previous one is that the input prompts have been formatted to per mit the input data to follow the input prompt on the same line. Although formally treated in Chapter 6, this example serves the purpose of introducing the student to some sim ple and useful formatting techniques. The input prompts are generated with a special formatted WRITE containing (1) an edit descriptor 1X, to properly specify carriage control, (2) a character field descriptor A, which specifies that the value to be written is a character constant, and (3) an edit descriptor $, which suppresses the normal carriage return, thereby permitting the input data to follow the input prompt on the same line. Example Program 4: Direct Screen Input with Formatted Input Prompts
2.11 SUMMARY
PROBLEMS
|
Documents in Portable Document Format (PDF) require Adobe Acrobat Reader 5.0 or higher to view; download Adobe Acrobat Reader. |
FORTRAN FOR SCIENTISTS AND ENGINEERS VICTOR M. PONCE • ONLINE EDITION • | |||||||
Copyright © 2014 • Victor M. Ponce • All rights reserved. |