Open and read data in one row in fortran 90

南笙酒味 提交于 2019-12-05 17:52:00

Each Fortran read statement, by default, reads a list of values and then advances to the beginning of the next line. Think of read as moving a cursor through the input file as it works. So your statement

read(100,*) test

does what you expect when the numbers in the input file are on separate lines. When they are all on the same line in the file the first read statement reads one value (i.e. test) then advances to the beginning of the next line to read the next value but there isn't a next line and you get the runtime error you have shown us.

There are 2 straightforward solutions.

One, you could read multiple values from a line in one statement, for example, you might declare

real, dimension(10) :: test

then

read(100,*) test

should get all the values into the array in one go.

Second, you could use non-advancing input, which tells the processor to not skip to the beginning of the next line after each read statement. Something like the following (check the edit descriptor for your circumstances)

read(100,'(f8.2)',advance='no') test

If you choose this latter approach, don't forget that after you have read all the values from a line you do want to skip to the beginning of the next line so you may need to execute a statement such as

read(100,*)

which doesn't read any values but does advance to the next line.

As already pointed out before, you can read your data in a row by adding

advance='no'

and a proper format string (depending on your data; for example 'i2' is working for a data sheet like [1 2 3 4 5 6] ) to your read command. Another useful trick is to additionally take care for the I/O status by writing it's value on a paramter (i.e. io) and exiting the do loop without the runtime error, even if you don't know the lenght of your data sheet. A complete program could for example look like:

program read
integer::a,io

open(100, file='data')
do
read(100,'(i2)',advance='no',IOSTAT=io)a
if (io<0) exit
if (io>0) stop 'problem reading'
write(*,*)a
end do

end program

Have fun!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!