Fortran无格式文件数据输出方法及severe(67)读写报错排查问询
核心问题解答
1. Fortran终端输出无格式文件数据的方法
Fortran没有直接write(*,*) 文件名这类直接打印整个二进制无格式文件的语法,你需要先按文件写入时的结构把数据读取到内存变量中,再把变量格式化输出到终端,示例代码如下(适配你提供的复数类型无格式文件):
program print_unformatted_file implicit none integer, parameter :: lun = 99 integer :: ios, i, lmax_file, nr_file real(kind=8) :: rmax_file integer(kind=1) :: spherical_file, linear_file, even_file double complex, allocatable :: Vc_file(:) open(unit=lun, file="chiral-RNN1000-Vlm-L01-R0400-NR00004", form='unformatted', iostat=ios) if (ios /= 0) stop "文件打开失败" ! 先读取文件头,匹配写入时的变量顺序和类型 read(lun) lmax_file, nr_file, rmax_file, spherical_file, linear_file, even_file print *, "文件头参数:lmax=",lmax_file," 总数据组数nr=",nr_file," rmax=",rmax_file ! 按读取到的lmax分配数组 allocate(Vc_file((lmax_file+1)**2)) ! 逐组读取并打印数据 do i = 1, nr_file read(lun) Vc_file print *, "第",i,"组数据:", Vc_file end do close(lun) end program print_unformatted_file
编译运行上述代码,即可把无格式文件中的所有内容打印到终端,和你预分配的Vlm数组做对比。
2. 报错"forrtl: severe (67): input statement requires too much data"的解决方法
该报错的本质是读取操作需要的数据量大于当前文件记录中剩余的数据量,针对你的场景排查点如下:
- 不要直接空读跳过文件头:你代码中
read(lun)空读跳过头的方式虽然理论上可以跳过第一条记录,但更稳妥的方式是完整读取头参数,同时校验参数是否匹配。你生成文件时头的变量顺序是integer(kind=4) lmax、nr→real(kind=8) rmax→integer(kind=1) spherical、linear、even,读取时要严格匹配变量类型和顺序,避免读取偏移。 - 校验循环次数是否匹配:你生成的文件中只有
nr=4组Vlm数据,要确认你代码中grid%nrp是否小于等于4,如果大于4就会出现数据不足的报错。 - 统一读写编译器:不同编译器生成的无格式文件记录头规则可能有差异,读写文件要使用同一款编译器,避免格式不兼容。
修改后的正确读取代码示例:
double complex, allocatable :: Vlm(:) ! 新增文件头变量定义,类型和顺序完全匹配写入逻辑 integer(kind=4) :: head_lmax, head_nr real(kind=8) :: head_rmax integer(kind=1) :: head_spherical, head_linear, head_even open(lun, file=vgrdfile, iostat=ios, form='unformatted') ! 完整读取文件头,同时做参数校验 read(lun) head_lmax, head_nr, head_rmax, head_spherical, head_linear, head_even if (head_lmax /= grid%Lmax) stop "文件lmax与grid%Lmax不匹配" if (head_nr < grid%nrp) stop "文件数据组数少于grid%nrp,数据不足" allocate(Vlm((grid%Lmax+1)**2)) do i = 1, grid%nrp read(lun) Vlm end do close(lun)
内容的提问来源于stack exchange,提问作者hh25
相关产品推荐
相关产品推荐

