在Fortran中读取具有已知行数但每行中未知条目数的数据文件

Zah*_*hur 2 fortran

如何读取包含已知行数的数据文件,但每行中的条目数是未知的,例如,如果我的数据文件包含某些内容,例如

1 3 4 5 6 -7 8 -9

1 3 5 6

4 5 6 7 8 3 5 6 7 8 4 5 7 8

即三条线,但每条线的数据是未知的.有一次我需要一行数据.

M. *_* B. 8

一种方法:使用至少与最长预期行一样长的字符串将行读入字符串.然后你去解析字符串.例如,如果数字总是按空格分割,则使用它来计算子字符串边界.然后,您可以使用"内部读取"从每个子字符串中读取以获取数值.内部读取使用字符串而不是单元号并从字符串中获取数据 - 至少您不必重新创建字符到数值的转换,read语句将为您执行此操作.Fortran提供的内部函数将使解析更容易.


小智 5

基于 MSB 指出的实现。很晚了,但我想这可能对某人有用。

准备好您希望读取的类型的数组:

double precision, dimension(MAX_NUM_OF_COLS) :: test_array
Run Code Online (Sandbox Code Playgroud)

从文件中读取一行:

READ(reading_unit,'(A)',iostat=io) line
Run Code Online (Sandbox Code Playgroud)

循环并尝试从该行读取最大数量的数字:

do i=1,MAX_NUM_OF_COLS
  READ(line, *, iostat=io) test_array(1:i)
  if(io==0) exit
enddo

write(*,*) 'number of columns = ', (i-1)
Run Code Online (Sandbox Code Playgroud)

如果需要,请在文件的所有行上循环此操作,并保留最大或最小列数。

最小示例:

integer, parameter :: MAX_NUM_OF_COLS=30
integer, parameter :: MAX_LINE_LENGTH=1000
character(len=MAX_LINE_LENGTH) line
integer i, io, reading_unit
double precision, dimension(MAX_NUM_OF_COLS) :: test_array

reading_unit=100
OPEN(reading_unit, file='the_file')

! Get first line of file.
DO
  READ(reading_unit,'(A)',iostat=io) line
  IF (io/=0) then
    write(*,*) "Error reading file."
    stop
  endif
  exit ! Eventually, do not exit and put the DO loop below here.
ENDDO
CLOSE(reading_unit)

do i=1,MAX_NUM_OF_COLS
  READ(line,*,iostat=io) test_array(1:i)
  if(io==-1) exit
enddo

write(*,*) 'number of columns = ', (i-1)
Run Code Online (Sandbox Code Playgroud)