Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

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

Avoid reading to new line

Status
Not open for further replies.

Samohtvii

Programmer
Aug 2, 2012
21
AU
If i have a text file say:
"dog cat mouse elephant"
and i want to read those into an char array the reader always just reads dog and then moves to a new line.
I don't know how many 'animals' will be in the text file so i can't just
read (7,*) animal(1), animal(2) etc, but i do know there isn't more than 50 so i can just allocate the char array.

Will i have to read them all in the check for spaces and seperate them then or is there some way to stay on the file line until an actual endline is found?

Thanks
 
The solution would be to use allocatable arrays.

Code:
character*20, allocatable, dimension (:) :: animal
integer nAnimal        ! counter
integer irslt

...
...

open (unit = 10, file = animal.txt)
nAnimal = 0

!  go through the file to count the number of entries
do
    read (10,*, iostat = irslt)
    if (irslt .ne. 0) exit
    nAnimal = nAnimal + 1
enddo

!  allocate array and read elements from file
allocate (animal (nAnimal))
rewind (10)
do irslt = 1, nAnimal
    read (10, *) animal (irslt)
enddo

If you want to avoid reading your file twice, you can use pointers and a linked list, but this is more complicated to handle but a good option if you have rather big files.

Norbert


The optimist believes we live in the best of all possible worlds - the pessimist fears this might be true.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top