阅读免费格式,无需提前

glu*_*uke 7 io file-io fortran

在给定的文件记录中,我需要先读取前两个整数元素,然后读取其余的行(大量真实元素),因为赋值取决于前两个.假设前两个的格式整数元素并没有很好地定义.

解决问题的最佳方法可能是:

read(unitfile, "(I0,I0)", advance='no') ii, jj
read(unitfile,*) aa(ii,jj,:)
Run Code Online (Sandbox Code Playgroud)

但在我看来,gfortran中不允许使用"(I0)"规范.

基本上,在unitfile中读取的文件可能是这样的:

0   0    <floats>
0   10   <floats>
10   0    <floats>
100   0    <floats>
100   100    <floats>
Run Code Online (Sandbox Code Playgroud)

很难用任何类似Fortran的固定字段格式规范来阅读.

有没有其他方法来解决这个问题,显然是微不足道的问题?

Ale*_*ogt 3

这应用字符串操作来获取各个组件,以空格' '和/或制表符 ( char(9)) 分隔:

program test
  implicit none
  character(len=256) :: string, substring
  integer            :: ii, jj, unitfile, stat, posBT(2), pos
  real, allocatable  :: a(:)

  open(file='in.txt', newunit=unitfile, status='old' )
  read(unitfile,'(a)') string

  ! Crop whitespaces
  string = adjustl(trim(string))

  ! Get first part:
  posBT(1) = index(string,' ')      ! Blank
  posBT(2) = index(string,char(9))  ! Tab
  pos = minval( posBT, posBT > 0 )

  substring = string(1:pos)
  string = adjustl(string(pos+1:))
  read(substring,*) ii

  ! Get second part:
  posBT(1) = index(string,' ')      ! Blank
  posBT(2) = index(string,char(9))  ! Tab
  pos = minval( posBT, posBT > 0 )

  substring = string(1:pos)
  string = adjustl(string(pos+1:))
  read(substring,*) jj

  ! Do stuff
  allocate( a(ii+jj), stat=stat )
  if (stat/=0) stop 'Cannot allocate memory'

  read(string,*) a

  print *,a

  ! Clean-up
  close(unitfile)
  deallocate(a)
end program
Run Code Online (Sandbox Code Playgroud)

对于像这样的文件in.txt

1 2 3.0 4.0 5.0
Run Code Online (Sandbox Code Playgroud)

这导致

./a.out 
   3.00000000       4.00000000       5.00000000
Run Code Online (Sandbox Code Playgroud)

注意:这只是一个简单的示例,请根据您的需要进行调整。