如何使用名单列表在派生类型中编写可分配数组?

时间:2016-08-05 02:57:11

标签: io fortran fortran2003 derived-types

使用命名列表编写嵌套在派生类型中的可分配数组时遇到问题。最小的例子如下所示。如何修改程序以使派生类型中的可分配数组工作,就好像它没有嵌套一样?

program test

    implicit none

    type struct_foo
        integer, allocatable :: nested_bar(:)
    end type struct_foo

    integer, allocatable :: bar(:)
    type(struct_foo) :: foo
    ! namelist / list / foo, bar
    namelist / list / bar

    allocate(bar(5))
    bar = [1:5]

    allocate(foo%nested_bar(5))
    foo%nested_bar=[1:5]

    write(*,list)

end program test

foo从名单中注释掉,它可以正常工作,产生输出:

 &LIST
 BAR     =           1,           2,           3,           4,           5
 /

包含foo后,程序无法编译:

>> ifort -traceback test_1.f90 -o test && ./test
test_1.f90(20): error #5498: Allocatable or pointer derived-type fields require a user-defined I/O procedure.
    write(*,list)
--------^
compilation aborted for test_1.f90 (code 1)

1 个答案:

答案 0 :(得分:3)

如错误消息所述,您需要提供用户定义的派生类型I / O(UDDTIO)过程。对于具有可分配或指针组件的任何对象的输入/输出,这是必需的。

如何在文件中格式化派生类型的对象完全受UDDTIO过程的控制。

下面是一个使用非常简单的输出格式的示例。通常,实现名称列表输出的UDDTIO过程将使用与namelist输出的其他方面一致的输出格式,并且通常还会有相应的UDDTIO过程,然后能够读回格式化的结果。

module foo_mod
  implicit none

  type struct_foo
    integer, allocatable :: nested_bar(:)
  contains
    procedure, private :: write_formatted
    generic :: write(formatted) => write_formatted
  end type struct_foo
contains
  subroutine write_formatted(dtv, unit, iotype, v_list, iostat, iomsg)
    class(struct_foo), intent(in) :: dtv
    integer, intent(in) :: unit
    character(*), intent(in) :: iotype
    integer, intent(in) :: v_list(:)
    integer, intent(out) :: iostat
    character(*), intent(inout) :: iomsg

    integer :: i

    if (allocated(dtv%nested_bar)) then
      write (unit, "(l1,i10,i10)", iostat=iostat, iomsg=iomsg)   &
          .true.,  &
          lbound(dtv%nested_bar, 1),  &
          ubound(dtv%nested_bar, 1)
      if (iostat /= 0) return
      do i = 1, size(dtv%nested_bar)
        write (unit, "(i10)", iostat=iostat, iomsg=iomsg)  &
            dtv%nested_bar(i)
        if (iostat /= 0) return
      end do
      write (unit, "(/)", iostat=iostat, iomsg=iomsg)
    else
      write (unit, "(l1,/)", iostat=iostat, iomsg=iomsg) .false.
    end if
  end subroutine write_formatted
end module foo_mod

program test
  use foo_mod

  implicit none

  integer, allocatable :: bar(:)
  type(struct_foo) :: foo
  namelist / list / foo, bar

  allocate(bar(5))
  bar = [1:5]

  allocate(foo%nested_bar(5))
  foo%nested_bar=[1:5]

  write (*,list)
end program test

使用UDDTIO显然需要一个实现此Fortran 2003语言功能的编译器。