Here's a modern Fortran program that reads the provided text file and processes the data into different zones. The program will store the data in arrays and print the contents of each zone.
Fortran Program
program read_zones
use, intrinsic :: iso_fortran_env, only : stderr => error_unit
implicit none
integer, parameter :: dp = kind(1.0d0)
integer, parameter :: max_zones = 10
integer, parameter :: max_points = 1000
character(len=50) :: zone_name
character(len=200) :: line
integer :: unit, i, j, num_points, zone_index
real(dp), allocatable :: x(:), y(:)
real(dp), allocatable :: zones_x(:,:), zones_y(:,:)
! Allocate space for up to max_zones zones, each with max_points points
allocate(zones_x(max_points, max_zones), zones_y(max_points, max_zones))
! Open the file
open(newunit=unit, file='zones.txt', status='old', action='read', &
iostat=i, iomsg=line)
if (i /= 0) then
write(stderr, '("Error opening file: ", a)') line
stop
end if
zone_index = 0
num_points = 0
do
read(unit, *, iostat=i) line
if (i /= 0) exit ! End of file or error
if (line(1:5) == 'zone ') then
! New zone detected
if (zone_index > 0) then
num_points = 0
end if
read(line, *) zone_name
zone_index = zone_index + 1
write(*, '("Reading zone: ", a)') trim(zone_name)
else
! Read point data
read(line, *, iostat=i) x(num_points+1), y(num_points+1)
if (i /= 0) then
write(stderr, '("Error reading point data: ", a)') line
stop
end if
num_points = num_points + 1
if (num_points > max_points) then
write(stderr, '("Too many points in zone: ", a)') trim(zone_name)
stop
end if
end if
end do
! Store points in zone arrays
do j = 1, zone_index
zones_x(1:num_points, j) = x(1:num_points)
zones_y(1:num_points, j) = y(1:num_points)
end do
! Close the file
close(unit)
! Print the contents of each zone
do j = 1, zone_index
write(*, '("Zone ", i0, ": ", a)') j, trim(zone_name)
do i = 1, num_points
write(*, '(2f12.6)') zones_x(i, j), zones_y(i, j)
end do
end do
! Deallocate arrays
deallocate(zones_x, zones_y)
end program
Explanation
-
File Reading:
- Opens the file
zones.txt.
- Reads lines and checks for
zone declarations.
- Stores points in temporary arrays
x and y.
-
Data Storage:
- Uses 2D arrays
zones_x and zones_y to store points for each zone.
- Each zone is stored in a column of these arrays.
-
Output:
- Prints the contents of each zone after reading.
Usage
- Save the provided text data into a file named
zones.txt.
- Compile and run the Fortran program.
Compilation
gfortran -o read_zones read_zones.f90
./read_zones
This program will read the file, store the data, and print the contents of each zone. Adjust max_zones and max_points if needed for larger datasets.