I would like to read coordinates from an from an input file. An example input file would look something like :
1 0.1542 0.2541 1.2451 N
12 4.5123 2.0014 2.0154 O
43 8.2145 0.2978 4.2165 H
etc... The size of this file is variable. The first column is a number assigned to an atom, the following columns are its x,y,z coordinates, and the final column is the elemental symbol of the atom.
I tried something along the lines of:
integer, allocatable :: atnum(:)
double precision, allocatable :: coord(:,:)
character(len=2), allocatable :: element(:)
open(unit=20, file='input', status='old',action='read')
read(20,*,end=200) atnum, coord(:,1:3), element
200 close(20)
This throws me the error:
Fortran runtime error: Bad integer for item 2 in list input
I assume that the program read the first entry into atnum(1)
, but then tried to continue reading into the second entry of the first row into atnum(2)
. How can I get it to read the input correctly?
I also think that there might be a problem with telling the program to read the middle three columns into coord(:,1:3)
. It is likely that it will read the first three entries into coord(1,1), coord(2,1), coord(3,1)
, then run into the character at the end of the line and become confused again. How can I tell it to fix the first subscript for the line, and read into the other dimension? Or will I have to swap the indices, like coord(1:3,:)
? Will that work?
EDIT: The above has been answered by tpg2114, but I still have a problem. I can't allocate the the array until I know how many sets of coordinates are to be read, but I only know how many atoms there are until I reach the end of the file. The program compiles fine if I don't allocate atnum, coord and element
, but returns a segmentation fault when I try to run it. How can I get it to read into the dynamic arrays without previously allocating them?
It sounds similar to this question: Variable size arrays in Fortran without Allocate()
Thanks in advance.