If you’re used to coding in more modern languages, Fortran I/O can seem a little bizarre. Strings in Fortran are much more difficult to work with, since they are fixed-length rather than null-terminated. The following example illustrates a simple way to read an array of numbers from a text file when the array length is unknown at compile time.
program io_test real, dimension(:), allocatable :: x integer :: n open (unit=99, file='array.txt', status='old', action='read') read(99, *), n allocate(x(n)) read(99,*) x write(*,*) x end
Here is the text file that the array is read from. The integer on the first line is the number of elements to read from the next line.
10 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0
7 thoughts on “Reading an array from a text file with Fortran 90/95”
Let me show (below) a slight modification in order to have the oneline string directly stored in a file. Cheers
real, dimension(:), allocatable :: x
integer :: n
open (unit=89, file=’447mono.dat’, status=’new’, action=’write’)
open (unit=99, file=’447km.dat’, status=’old’, action=’read’)
read(99, *), n
Nice work, however I’m not able to use this in ifort… how is your txt file formated? I’m trying to use comma separated files…
Oh, sorry, I got it… but having to specify the size of the array in the first line of the text won’t work for me… but indeed, this is a simple method…
Hi martin, am having similar problem, it works fine if i specify the size of the array. Please I need to obtain the length of the array without specifing the size at the beginning,please How do i go about it.
Ade, you have to know the length of the data before reading it into an array. This is a fundamental limitation of Fortran. If you have to read files of unknown length, you will have to read each file twice. Read a file once to determine the length, allocate the array, and then read in the data.
Run through the file once to get the no of lines.
Here n contains the no of lines in the data file.
Later n can be used in several ways. To read the data in to array now,