fortran - 使用fortran从文件中读取整数数据
问题描述
我正在尝试从文件中读取整数列表(长度未知)并将其保存为数组。我认为我做的一切都是正确的,但这些值没有被读入数组。我知道有很多这样的问题,但我无法发现我的代码的问题。有人可以帮我找出我在代码/方法中犯的错误吗?整数列表如下所示:
3
4
90
1267
1668
49
570
1271
这是我的代码:
PROGRAM read_nodes
implicit none
integer :: n, ios,i, count_lines
logical :: existfile=.FALSE.
integer,dimension(:), allocatable :: hnset_nodes, nodes, tmp
character(len=80) :: input_line, filename='CooledNodes.txt'
allocate(nodes(5))
INQUIRE(file=filename, exist=existfile) ! check if file exists
IF (existfile) then
print*, 'File exists'
ELSE
write(*,*) 'ERROR: The file "CooledNodes.txt" does not exist'
stop
END IF
n = count_lines(filename) ! find number of lines in file
print*, 'number of lines=', n
if(n>size(nodes)) then
allocate(tmp(n))
tmp(1:size(nodes)) = nodes
call MOVE_ALLOC(tmp, nodes)
end if
print*, 'size of array=', size(nodes)
open(unit=10, file='CooledNodes.txt', status='old', action='read')
DO i=1,n
read(10,*, iostat=ios) nodes(i)
print*, 'reading'
print*, nodes(i)
if(ios<0) exit
END DO
allocate(hnset_nodes(n), stat=ios)
!if(ios==0) then
!print*, 'array size=', size(hnset_nodes)
!end if
hnset_nodes=nodes
open(unit=15, file='nodes.txt')
write(15, fmt='(I5)') hnset_nodes ! writes the values read as a verification step.
END PROGRAM read_nodes
integer function count_lines(filename)
implicit none
character(len=80) :: filename
integer :: ios, nlines=0
logical :: existfile=.false.
open(unit=10, file='CooledNodes.txt', status='old', action='read')
print*, 'File opened'
DO
read(10, *, iostat=ios) ! counting number of lines in the file
if (ios/=0) exit
print*, 'reading file'
nlines=nlines+1
END DO
count_lines= nlines
end function count_lines
代码执行没有任何错误,但将零打印到文件中。似乎它根本不读取文件中的值。
解决方案
推荐阅读
- c# - WPF ProgressBar 从另一个类更新
- python - 如何使用 HTTPBasicAuth 注释测试 Flask 路由器方法
- python - Python / Pandas Dict 找到最接近的匹配然后结束循环
- javascript - 解析 json 反应原生
- javascript - 如何在数组中搜索单词?
- c++ - 使用 CMake 在生成的 Makefile 中正确添加自定义命令的最佳方法是什么?
- php - 来自的邮件无法正常工作(来自电子邮件地址的显示不正确)
- swift - 在 tvOS 上运行时动态调整 UITableViewCell 的大小
- powershell - 检查word文件是否在powershell中受密码保护
- php - Symfony - 更新唯一的 OneToMany 关系属性