An open file should be closed when it is no longer needed. The general form of a close statement is:
close(<unit number>)
Where the the unit number was assigned during the initial open.
For the previous examples, close(10) close(12)
would be used to close the opened files.
12.7 Example
In this example we will write a Fortran program to read an input file and write a line number and the original line to an output file.
12.7.1 Understand the Problem
For this problem, we will read get the file names from the user and open the files. Then we will read a line from the input file, and write the line number and line to the output file. When done, we will close the file.
12.7.2 Create the Algorithm
For this problem, first we will need to prompt for and read the file names from the user and ensure that they open correctly. If the file can not be opened, an error message will be displayed and the file names will be re-read.
Once the file is open, a line will be read from the input file, and the line number and the line will be written to the output file. For this example, we will assume that a line will have 132 or less characters.
Chapter 12 ◄ File Operations This process will continue until there are no more lines in the input file.
! loop
! read line from input file
! if end of file, exit loop
! write line number and line to output file
! close files
For convenience, the steps are written a program comments.
12.7.3 Develop the Program
Based on the algorithm, the below program could be developed.
program linenumbers
Chapter 12 ► File Operations
! read output file name read(*,*) wrfile
! open output file (read access)
! if open unsuccessful, display error message
! otherwise, end loop
open(14, file=wrfile, status="replace", &
action="write", position="rewind", &
iostat=wropst ) if (wropst==0) exit
write(*,'(a/,a)') "Unable to open output file.", &
"Please reenter"
end do
!
i = 1 do
! read line from input file
read(12, '(a)', iostat=rdst) line
! if end of file, exit loop if (rdst >0) stop "read error"
if (rdst <0) exit
! write line number and line to output file write(14, '(i10,2x,a)') i, line
i = i + 1 end do
! close files close(12) close(14)
end program linenumbers
The spacing and indentation is not required, but helps to make the program more easily readable.
12.7.4 Test/Debug the Program
For this problem, the testing would involve executing the program with various input files and verifying that the line numbers are correctly added.
12.8 Exercises
Below are some quiz questions and project suggestions based on this chapter.
Chapter 12 ◄ File Operations
12.8.1 Quiz Questions
Below are some quiz questions.
1) What must occur before a file can be read or written?
2) What is the range of the valid unit numbers for a file open?
3) For the following statements:
integer :: opnstat
character(20) :: filename="file.txt"
open (14, file=filename, status="old", action="read",
& position="rewind", iostat=opnstat) if ( opnstat > 0 ) then
write (*, *) "Error, can not open file."
stop end if
a) What is the name of the file being opened?
b) What is the unit number that will be used for subsequent write operations?
c) Does the error message get printed if the file does not exist (yes/no)?
d) What does it mean when the status variable is > 0?
4) Assume the file answers.txt exists, has been successfully opened using unit number 20, and contains the following data:
"line 1 data1=23 data2 =034 data3 =05123"
What is the read statement required to get data1, data2, and data3 into the integer variables num1, num2, and num3 respectively.
12.8.2 Suggested Projects
Below are some suggested projects.
1) Type in the line numbers program, compile, and execute the program. Test the program on a number of different input values.
Chapter 12 ► File Operations
2) Imagine the movement of a small circle that rolls on the outside of a rigid circle. Imagine now that the small circle has an arm, rigidly attached, with a plotting pen fixed at some point. That is a epicycloid, commonly called a spirograph7. Write a Fortran 95 program to
generate the (x,y) coordinates for a spirograph drawing.
First, the program should prompt for an output file name, read the file name, and open the file.
If the file can not be opened, the program should display an appropriate error message and re-prompt. Next, the program should prompt for a read radius 1 (fixed circle), radius 2 (moving circle), offset position (rigid arm length). The radius 1, radius 2, and offset position values must be between -100 and +100 (inclusive). If any value is out of range, the program should re-prompt. If the user does not enter a valid file name or number of input values after three tries, the program should terminate with an appropriate error message. That is, three errors are acceptable, but if a fourth error is made, the program should terminate. The prompts and subsequent reads should be on the same line (see example).
Then, the program should generate (x,y) points based on one the following formulas:
x=((radius1+radius2) ∗cos( step)) +
(
offsetposition ∗ cos(
(radius1+radius2) ∗radiusstep 2) )
y =((radius1+radius2) ∗sin (step)) +
(
offsetposition ∗ sin(
(radius1+radius2) ∗radiusstep 2) )
The step should start at 0.0 and stop at 360.0, stepping by 0.1. All writes should use a formatted output (not the '*'). Then the program should close the output file, inform the user the plotting is completed. Test the program on a number of different input values.
3) Write a Fortran program that plays the Chaos Game. To play the Chaos Game, plot 3 points A, B, C and an arbitrary initial point X1. Then, generate a random number between 1 and 3 representing A, B, or C. If A comes up, plot the midpoint of the line joining X1 to A. If B comes up, plot the midpoint of the line joining X1 to B; the case with C is similar. Call this new point X2. Roll the die again. Plot the midpoint of the line joining X2 to either A, B or C depending on the outcome of the die toss. Call this new point X3. Repeat this process N times.
Test the program on a number of different input values.
Refer to Appendix C for more information regarding generating random numbers.
Note, the correct output of this program is shown on the cover page.
7 For more information, refer to: http://en.wikipedia.org/wiki/Spirograph
13 Single Dimension Arrays
An array is a collection or set of data. A variable can hold a single value. An array can hold multiple values. The type (i.e., integer, real, etc.) of each item in the array must be the same. In order to access specific elements an index or subscript is used. The index specifies which element or value in the array.
An array is consider a direct access structure since any element can be accessed directly, without accessing any other elements.
The most basic form of an array is a single dimension array. A single dimension array can be thought of as a single column in a spreadsheet. The column name, like A, is the array name and the row number is like the index.
For example, a single dimension array might look like:
index value
Array Name 1 <value>
2 <value>
3 . . .
. . .
<value>
n <value>
The specific syntax requires an index or subscript to specify which element of the array to access. By default, the first element is at index=1, the next at index=2, and so forth. This can be changed if needed.