fortran - 如何使用while循环在fortran中读取文件?
问题描述
我正在尝试使用 Fortran 代码读取文本文件。我有一个包含 1999 行的文件,每行的列数不同。有人可以告诉我如何编写这样的问题。这是我用于读取 4*2 文本文件的代码,但我正在使用在当前情况下无法使用的 do 循环。
PROGRAM myread2
IMPLICIT NONE
INTEGER, DIMENSION(100) :: a, b
INTEGER :: row,col,max_rows,max_cols
OPEN(UNIT=11, file='text.txt')
DO row = 1,4
READ(11,*) a(row), b(row)
END DO
PRINT *, a(1)
PRINT *, a(4)
PRINT*, b(4)
END PROGRAM myread2
解决方案
像这样读取文件的最佳方式取决于您希望如何存储数据。我将使用一个参差不齐的数组,因为它可能是最简单的,尽管根据您的要求,其他容器类型可能更适合。
Fortran 本身没有参差不齐的数组,因此首先您需要定义一个类型来保存每一行。这可以作为
type :: RowData
integer, allocatable :: cols(:)
end type
type(RowData), allocatable :: rows(:)
当这个容器被填满时,第 ' 行i
第 ' 列中的值j
将被访问为
value = rows(j)%cols(i)
然后我们可以编写一个程序来读取文件,例如
type :: RowData
integer, allocatable :: cols(:)
end type
type(RowData), allocatable :: rows(:)
integer :: no_rows
integer :: i
open(unit=11, file='text.txt')
no_rows = count_lines(11)
allocate(rows(no_rows))
do i=1,no_rows
rows(i)%cols = read_row(11)
enddo
现在我们只需要编写函数count_lines
来计算文件中的行数,以及read_row
从文件中读取一行并将该行的内容作为整数数组返回。
按照这个问题,count_lines
可以写成
! Takes a file unit, and returns the number of lines in the file.
! N.B. the file must be at the start of the file.
function count_lines(file_unit) result(output)
integer, intent(in) :: file_unit
integer :: output
integer :: iostat
output = 0
iostat = 0
do while (iostat==0)
read(file_unit, *, iostat=iostat)
if (iostat==0) then
output = output+1
endif
enddo
rewind(file_unit)
end function
编写read_row
,从文件中解析未知长度的行,可以按照这个问题来完成。
推荐阅读
- node.js - Module.create 不从输入中获取数据,req.body 为空
- python - ValueError:操作数无法与形状一起广播 (720,1280) (720,1281)
- mysql - 这三个查询之间是否有任何性能差异
- java - Intellij 搜索某些类不工作,但到处搜索工作
- c# - 从下拉列表中选择值后显示文本框值(应显示从下拉列表中选择产品后的产品数量)
- python - 绘制不同子图中各种连续变量的密度
- javascript - 重定向到特定页面的问题
- excel - 如果工作表上的单元格值与另一张表上的单元格值相同,则删除该行
- ag-grid - 如何在 ag-grid 中为特定列自定义分组值?
- docker - 容器以 docker-compose up 开头,以 docker ps 列出,然后不以 docker-compose 出现