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 FNUMand FSTREAMintrinsics. 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” (page 108)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 writesystem 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 WRITEstatement, the program uses theALIASdirective to avoid the conflict by referring to write as IWRITE.)

Example 29 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 written; if the write was successful, it should be 10 status=IWRITE(fd, a, 10)

CLOSE (1, STATUS=’KEEP’)

!open the file for reading; we want to see if the write was

!successful

OPEN (1, FILE='file1', STATUS='UNKNOWN') READ (1, 4) (a(i), i = 1, 10)

4 FORMAT (10A1)

CLOSE (1, STATUS='DELETE') DO i = 1, 10

!if we find anything other than x's, the write failed IF (a(i) .NE. 'x') STOP 'FNUM_TEST failed'

END DO

!check write's return value; it should be 10

IF (status .EQ. 10) PRINT *, 'FNUM_TEST passed'

END

Below are the command lines to compile, link, and execute the program, followed by the output from a sample run.

$ f90 fnum_test.f90 $ a.out

FNUM_TEST passed

The HP Fortran Programmer's Referencedescribes theFNUM and FNUMintrinsics and the ALIASdirective. For information about the write system routine, see the write((2))man page.

File handling 121