next up previous
Next: 6- Initialization Up: Interfacing Fortran and Previous: 4- Calling Fortran

5- Input/Output

With few exceptions, mixing Fortran and C input/output calls is asking for trouble. Often the runtime libraries of both languages implement separate buffering schemes in order to improve performance.

Terminal Input

One should never mix READ(5,...) and
fgets(...,stdin) requests. On most systems it works as long as the input device is really a terminal. However, at the latest when stdin is connected to a file or a pipe the Fortran READ will suck in more than just its share to satisfy the immediate request. Any following fgets will then access the wrong information (or report end-of-file).

Terminal Output

Mixing WRITE(6,...) and fprintf(stdout,...) is safe as long as the output device is the terminal. When stdout is redirected the C stream functions usually start buffering the output.

On a number of Unix systems (RS/6000, Alpha/OSF, Ultrix) the Fortran runtime library does not use the C stream functions, and the Fortran and C output buffers are flushed out of sequence. The C runtime libraries on these systems can be told to limit themselves to line buffering by

  if( !isatty( fileno(stdout) ) )
    setlinebuf( stdout );

It seems that the Fortran runtime libraries are already disciplined enough to use for WRITE(6,...) and PRINT ... only line buffering. Note that setlinebuf is not a standard Unix function. Hopefully, if it is not contained in stdio.h, it also is not necessary.

Formatted I/O

There is no general way to associate a Fortran logical unit number with a C FILE* stream. KUIP offers C functions ku_read and ku_write as a convenient interface to Fortran I/O statements for reading/writing complete lines. For details refer to the KUIP manual.

(Note that even in Fortran a READ(LUN,'(A)') CHLINE is not portable because the VS-Fortran runtime library is not able to handle V-format files.)

Unformatted I/O

Some systems provide a function getfd to inquire about the C file descriptor associated to a Fortran logical unit number. This is however non-standard, and often Fortran unformatted sequential I/O adds system-dependent control information to allow for variable length records.

The CIO package in KERNLIB provides a Fortran callable set of interface routines to the C read and write functions in order to perform system-independent unformatted I/O, both for sequential and direct access with fixed record sizes.



next up previous
Next: 6- Initialization Up: Interfacing Fortran and Previous: 4- Calling Fortran



Janne Saarela
Mon May 22 15:43:10 METDST 1995