首页 > 解决方案 > 如何使用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

解决方案


像这样读取文件的最佳方式取决于您希望如何存储数据。我将使用一个参差不齐的数组,因为它可能是最简单的,尽管根据您的要求,其他容器类型可能更适合。

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,从文件中解析未知长度的行,可以按照这个问题来完成。


推荐阅读