Number of lines of a text file

前端 未结 1 2009
孤街浪徒
孤街浪徒 2020-12-20 03:06

I\'m trying to make a function that takes in a file name (i.e. \"data.txt\") and produces the number of lines of that file.

data.txt :
24 42
45 54
67 76
89 9         


        
相关标签:
1条回答
  • 2020-12-20 03:19

    filename (the dummy argument) is only one character long. Anything might happen if you provide a longer one (usually it is capped, though). This does not result in an error as you did not specify the status of the file, or even checked whether the operation was successful (In fact, you just created a new file d). You can avoid this by using an assumed length string:

    function count_lines(filename) result(nlines)
      character(len=*) :: filename
      ! ...
    
      open(10,file=filename, iostat=io, status='old')
      if (io/=0) stop 'Cannot open file! '
    
    function count_lines(filename) result(nlines)
      implicit none
      character(len=*)    :: filename
      integer             :: nlines 
      integer             :: io
    
      open(10,file=filename, iostat=io, status='old')
      if (io/=0) stop 'Cannot open file! '
    
      nlines = 0
      do
        read(10,*,iostat=io)
        if (io/=0) exit
        nlines = nlines + 1
      end do
      close(10)
    end function count_lines
    

    [Increment after the check to ensure a correct line count.]


    For the second part of your question:

    Positive (non-zero) error-codes correspond to any error other than IOSTAT_END (end-of-file) or IOSTAT_EOR (end-of-record). After reading in the (new) file in the first round of the loop (io==IOSTAT_END, I checked with my compiler), you are trying to read beyond the end... This results in a positive error. Since the increment occurs before you exit the loop, the final value is 2.

    0 讨论(0)
提交回复
热议问题