HP Fortran Programmer's Guide (B3908-90031; September 2011)

Calling C routines from HP Fortran
File handling
Chapter 8 199
File handling
A Fortran unit number cannot be passed to a C routine to perform I/O on the associated file; nor can a C file
pointer be used by a Fortran routine. However, a file created by a program written in either language can be
used by a program in the other language if the file is declared and opened within the program that uses it.
C accesses files using HP-UX I/O subroutines and intrinsics. This method of file access can also be used
from Fortran instead of Fortran I/O.
You can pass file units and file pointers from Fortran to C with the FNUM and FSTREAM intrinsics. FNUM
returns the HP-UX file descriptor corresponding to a Fortran unit, which must be supplied as an argument;
see “Establishing a connection to a file” on page 178 for information about file descriptors. FSTREAM
returns C's file pointer for a Fortran unit number, which must also be supplied as an argument.
The following Fortran program calls the write system routine to perform I/O on a file, passing in a file
descriptor returned by FNUM. (Because of the name conflict between the write system routine and the
Fortran WRITE statement, the program uses the ALIAS directive to avoid the conflict by referring to write
as IWRITE.)
Example 8-9 fnum_test.f90
PROGRAM fnum_test
! Use the ALIAS directive to rename the "write" system routine.
! The built-in functions %VAL and %REF indicate how the
! arguments are to be passed.
!$HP$ ALIAS IWRITE = 'write' (%VAL, %REF, %VAL)
CHARACTER*1 :: a(10)
INTEGER :: i, fd, status
! fill the array with x's
a = 'x'
! open the file for writing
OPEN(1, FILE='file1', STATUS='UNKNOWN')
! pass in the unit number and get back a file descriptor
fd = FNUM(1)
! call IWRITE (the alias for the "write" system routine),
! passing in three arguments:
! fd = the file descriptor returned by FNUM
! a = the character array to write
! 10 = the number of elements (bytes) to write
! the return value, status, is the number of bytes actually