- Fortran使用read( )函数读取数据的时候,通常情况下是一次读取一行内容。当文件中的数据是几行组成的数据块的时候,这样读取数据就不太方便。我们可以使用"/"符号进行换行操作,以完成一次read( )读取多行数据。
- 数据格式如下:
Jack 1 180****8881 China
177.25 70.2
Jaasf 2 180****8882 USA
177.25 70.2
Moda 3 180****8883 China
177.25 70.2
可以看到每两行构成一个数据块。
- 上代码:
program ex_ReadData
implicit none
type student
character(len = 20) :: name
integer(kind = 4) :: ID
character(len = 20) :: tel
character(len = 20) :: address
real(kind = 4) :: height
real(kind = 4) :: weight
endtype student
type(student) :: class01(5)
integer(kind = 4) :: i, j
character(len = 100) :: fom = "(A7, I3.2, A15, A8, / ,2(f7.2))"
i = 0
open(UNIT = 156, file = "ex011.dat", ERR=300)
do
read(UNIT = 156, FMT = fom, END = 200) class01(i+1)%name , class01(i+1)%ID, &
class01(i+1)%tel , class01(i+1)%address, &
class01(i+1)%height, class01(i+1)%weight
i = i + 1
write(*,"(A10, I3,A15)") "读入第:", i, "个学生数据"
enddo
200 write(*, *) "文件读取结束"
close(UNIT = 156)
do j = 1, i
write(*, fom) class01(j)%name , class01(j)%ID, &
class01(j)%tel , class01(j)%address, &
class01(j)%height, class01(j)%weight
write(*, *) "-----------------------------------------------------"
enddo
stop
300 write(*, *) "文件打开失败!"
end program ex_ReadData
- 执行结果如下:
- 可以看出在write数据的时候依然可以使用同样的方法一次性输出多行数据。