首页 > 解决方案 > 使用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

代码执行没有任何错误,但将零打印到文件中。似乎它根本不读取文件中的值。

标签: fortran

解决方案


推荐阅读