Fortran 读取文件并存储到数组:wind.txt 示例
以下是使用 Fortran 实现将每一列的数值存入不同数组的示例代码:
program read_wind_file implicit none integer :: i, n real :: x, y, z real, dimension(:), allocatable :: col1, col2, col3 open(10, file='wind.txt') n = 0 do while (.true.) read(10,,iostat=i) x, y, z if (i/=0) exit n = n + 1 end do allocate(col1(n), col2(n), col3(n)) rewind(10) do i=1,n read(10,) col1(i), col2(i), col3(i) end do close(10) ! print out the arrays for verification do i=1,n write(,) col1(i), col2(i), col3(i) end do end program read_wind_file
在这个例子中,我们首先打开文件 wind.txt,并将文件中的每一行读入一个实数 x、y 和 z。我们使用 iostat 标记来检测文件是否读完,如果读完了,则退出循环。在读取完整个文件后,我们使用 allocate 语句为每个数组分配内存。然后我们将文件指针重新定位到文件开头(使用 rewind),并再次遍历文件,将每列的数值存入相应的数组中。最后,我们关闭文件,并使用一个循环来打印输出每个数组的内容以进行验证。
原文地址: https://www.cveoy.top/t/topic/nF5j 著作权归作者所有。请勿转载和采集!