title: Number of lines of a text file
body: <p>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.</p>
  
  <pre><code>data.txt :
  24 42
  45 54
  67 76
  89 98
  12 21
  99 99
  33 33
  </code></pre>
  
  <p>The below piece of code is my attempt to build a function that takes in the filename "data.txt" and produces the number of lines of the file. The first part (lines 1-12) of the code is defining the function and the second part (lines 14-19) is where I call the function in a program. The output of the below code is 1 rarther than 7 (look up - data.txt has 7 lines).</p>
  
  <pre><code>function count_lines(filename) result(nlines)
    character :: filename
    integer :: nlines 
    open(10,file=filename)
    nlines = 0
    do
    read(10,*,iostat=io)
    nlines = nlines + 1
    if (io/=0) exit
    end do
    close(10)
  end function count_lines
  
  program myread 
    integer :: count_lines
  
    print *, count_lines("data.txt")
  
  end program myread
  </code></pre>
  
  <p>Attempt a debuging:</p>
  
  <p>I think it has something to do with the do loop not working, but I'm unsure. I have changed the if statement to <code>if (io&gt;0)</code> and this gives an output of <code>2</code>, which I don't understand. At present I'm not getting an error outputs when I compile just the wrong output.</p>