HP Fortran Programmer's Reference (September 2007)

I/O and file handling
Example programs
Chapter 8228
Example programs
This section gives example programs that illustrate I/O and file-handling features of HP
Fortran.
Internal file
The following example, int_file.f90, illustrates how internal files can use edit descriptors
internally. The comments within the program explain in detail what the program does.
Example 8-1 int_file.f90
! The main program is a driver for the function roundoff, which
! truncates and rounds a floating-point number to a requested
! number of decimal places. The main program prompts for two
! numbers, a double-precision number and an integer. These are
! passed to the function roundoff as arguments. The
! double-precision argument (x) is the value to be rounded, and
! the integer (n) represents the number of decimal places for
! rounding. The function converts both arguments to character
! format, storing them in separate internal files. The function
! uses the F edit descriptor (to which n in character format has
! been appended) to round x. This rounded value is finally
! converted back from a character string to a double-precision
! number, which the function returns.
PROGRAM main
REAL (KIND=8) :: x, y, roundoff
! Use nonadvancing I/O to suppress the newline and keep the
! prompt on the same line as the input.
WRITE (6, '(X, A)', ADVANCE='NO') 'Enter a real number: '
READ (5, '(F14.0)') x
WRITE (6, '(A)') 'How many significant digits (1 - 9) to the'
WRITE (6,'(X, A)',ADVANCE='NO') 'right of the decimal point? '
! Don’t enter a number greater than you input into x!
READ (5, '(I1)') n
y = roundoff(x, n)
PRINT *, y
END PROGRAM main
! This function truncates and rounds x to the number of decimal
! places specified by n. The function performs no error
! checking on either argument.
REAL (KIND=8) FUNCTION roundoff(x, n)
INTEGER :: n