user1133418
user1133418

Reputation: 33

How to read a data file with an unknown structure in FORTRAN?

I need to read files that contain an undefined number of cells and for each cell an unknown number of data pairs. I am using Fortran.

The file looks like that:

Cell Number 1
Depth1 Volume1
Depth2 Volume2
Depth3 Volume3
.
.
.
Cell Number N
Depth1 Volume1
Depth2 Volume2
Depth3 Volume3
Depth4 Volume4
Depth5 Volume5

Can somebody help me?

Upvotes: 1

Views: 1855

Answers (2)

M. S. B.
M. S. B.

Reputation: 29401

As answered by @yosukesabia, you probably want to use the standard approach of reading into a string, and then looking at the string to decide what you just read, then based on that doing an internal read from the string.

But there is also the issue of how to store the data once you have read it ... Since you have both an unknown number of cells and an unknown number of data items per cell, the most elegant approach would be to create a linked list type for each. To have a list of cells, and when you encounter a new cell, add to that list. And the cell type itself contain a list of cell-data type list. When you encounter a new data item, you add to that list. A linked list is probably the best way to handle an unknown number of items. A recent question pertained to linked lists in Fortran: How can I implement a linked list in fortran 2003-2008. Otherwise you could read the file, rewind or backspace, and allocate arrays of the correct size, then re-read. The primitive way is to have fixed length arrays of the types, sized at the maximum possible number of cells, and the maximum possible number of data items per cell. Simple, but very inelegant. And bug prone if your guess of the maximum number is wrong.

Upvotes: 4

yosukesabai
yosukesabai

Reputation: 6244

which version of fortran are you using? 95?

read in as a character(len=1000) or something long enough, and then read from that variable.

program xx
character(len=1000) :: buf
integer :: celnum
open(11,file='dat.txt',status='old')

do
   read(11,'(a)') buf
   print*,buf(1:12)
   if (buf(1:12)=='Cell Number ') then
     read(buf(13:1000), *) celnum
     print *, celnum
   elseif (buf(1:5) == 'Depth') then
     ! here it is not clear what I am suppose to read
   else
     print*,'que?'
     stop
   endif

enddo
end

Upvotes: 2

Related Questions