Our first program will demonstrate file reading operations in Fortran. Here’s the full source code:
This Fortran program demonstrates various file reading operations. Let’s break it down:
We start by defining variables for file operations and a helper subroutine check to handle errors.
The program first reads the entire contents of the file ‘/tmp/dat’ and prints it.
Then, it demonstrates reading specific parts of the file:
Reading the first 5 bytes
Seeking to the 6th byte and reading 2 bytes
Fortran doesn’t have built-in functions for some operations like Seek, so we use alternative methods like reading and discarding data to move the file pointer.
Error checking is done after each file operation using the check subroutine.
To run the program, save it as file_reading.f90 and compile it using a Fortran compiler:
Make sure to create the ‘/tmp/dat’ file with some content before running the program:
This example demonstrates basic file reading operations in Fortran. While Fortran doesn’t have some of the more advanced file handling features of modern languages, it provides sufficient functionality for most file reading tasks.