Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations IDS on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

read an unknown number of lines into arrays

Status
Not open for further replies.

tuli

Electrical
Feb 20, 2003
16
Hello,

I need to read in an unknown number of array elements. i do not know how to handle the dimension of the arrays.
I start with declaring the size of each array as 101, but the file includes an unknown number of array components so I would nee to resize the array, which cannot be done in the middle of the code. the data file is attached (Here is the code for now:

program main
parameter(imax=101)
dimension th(imax),et1(imax),et2(imax),eph1(imax),eph2(imax)
open(5,file="farfields.txt")
read(unit=5, fmt='(a1)') dummy ! read dummy text
read(unit=5, fmt='(a1)') dummy ! read dummy text
read(5,*) npoints,freq,phi

m=1
! form here on i need to read 5 arrays and I do not know the size of the file.
100 read(5,*,end=101) th(m),et1(m),et2(m),eph1(m),eph2(m)
print*,m,th(m),et1(m),et2(m),eph1(m),eph2(m)
m=m+1
goto 100
101 continue
mmax=m-1
print*,'mmax= ',mmax
close(5)

stop
end program main
 
Replies continue below

Recommended for you

Well, if you do not know the number of entries, you could simply take one pass through the file reading entire lines at a time just like you did before with dummy and, of course, count how many line there are in the file...

....then, allocate your arrays; which they shouldn't be declared with fixed length in the first, you need to declare them without size "dimension:))" and allocatable.

...then, rewind the file and start over; this time, read the individual values for each array entry.


Then again, it seems to me that the number of entries in the arrays ARE known, you are already reading such value into your variable npoints...so, a program to read that with dynamically allocated arrays would look somethin like this:


program main
character dummy*120
integer npoints
real freq,phi
real, dimension:)), allocatable :: th,et1,et2,eph1,eph2

open(15,file="farfields.txt")

read(15,'(a)') dummy
read(15,'(a)') dummy
read(15,*) npoints,freq,phi

allocate(th(npoints))
allocate(et1(npoints))
allocate(et2(npoints))
allocate(eph1(npoints))
allocate(eph2(npoints))

do i=1,npoints
read(5,*) th(m),et1(m),et2(m),eph1(m),eph2(m)
end do

close(5)

! do whatever you need to do with array data

stop
end program main


 
The third line of your data file is "361 3.800000 0.0000000E+00"

There are 361 lines of data after the third line, therefore you only need to initially read in the first three lines to discover the size of array required.

quality, cost effective FEA solutions
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor