A new “stream” I/O scheme of the Fortran 2003 standard is implemented in f95. Stream I/O access treats a data file as a continuous sequence of bytes, addressable by a positive integer starting from 1. Declare a stream I/O file with the ACCESS=’STREAM’ specifier on the OPEN statement. File positioning to a byte address requires a POS=scalar_integer_expression specifier on a READ or WRITE statement. The INQUIRE statement accepts ACCESS=’STREAM’, a specifier STREAM=scalar_character_variable, and POS=scalar_integer_variable.
Stream I/O is very useful when interoperating with files created or read by C programs, as is shown in the following example:
Fortran 95 program reads files created by C fwrite() program reader integer:: a(1024), i, result open(file="test", unit=8, access="stream",form="unformatted") ! read all of a read(8) a do i = 1,1024 if (a(i) .ne. i-1) print *,’error at ’, i enddo ! read the file backward do i = 1024,1,-1 read(8, pos=(i-1)*4+1) result if (result .ne. i-1) print *,’error at ’, i enddo close(8) end C program writes to a file #include <stdio.h> int binary_data[1024]; /* Create a file with 1024 32-bit integers */ int main(void) { int i; FILE *fp; for (i = 0; i < 1024; ++i) binary_data[i] = i; fp = fopen("test", "w"); fwrite(binary_data, sizeof(binary_data), 1, fp); fclose(fp); } |
The C program writes 1024 32-bit integers to a file using C fwrite(). The Fortran 95 reader reads them once as an array, and then reads them individually going backwards through the file. The pos= specifier in the second read statement illustrates that positions are in bytes, starting from byte 1 (as opposed to C, where they start from byte 0).