title: Fortran read() reads last line twice?
body: <p>So, suppose I'm trying to read in a file the length of which I don't know before hand. We can use iostat and a while loop to break when we need to, but I'm having an issue with this. Namely, the code I've written reads the last line twice. I'm sure there is an obvious solution, but I can't seem to figure it out. I don't really understand how either the read() or iostat functions work entirely (I'm pretty new at fortran), but I can't glean much from documentation so I'm hoping someone here can help. </p>
  
  <p>Here is the (relevant bit of) code I've written: </p>
  
  <pre><code>filename = 'test.txt' 
  iostat_1 = 0 
  iostat_2 = 0 
  open(newunit = lun, file = filename, status = 'old', iostat = iostat_1) 
  if (iostat_1 == 0) then 
      do while(iostat_2 == 0)             
          if(iostat_2 == 0) then 
              read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1                   
              print *, dum, real_1,real_2,int_1                  
          endif
      enddo
  endif
  </code></pre>
  
  <p>So, supposing my input file is </p>
  
  <pre><code>1 1.0 1.0 1
  2 2.0 2.0 1 
  3 3.0 3.0 1
  4 4.0 4.0 4 
  </code></pre>
  
  <p>Then the output to the terminal from the print statement will be </p>
  
  <pre><code>1 1.0 1.0 1
  2 2.0 2.0 1 
  3 3.0 3.0 1
  4 4.0 4.0 4 
  4 4.0 4.0 4 
  </code></pre>
  
  <p>So keep in mind the following: The main purpose here is to be able to read in a file with an arbitrary number of lines. I'm not interested in a solution involving reading the number of lines first. </p>
  
  <p>Thanks for the help! </p>
  
  <p><strong>UPDATE Okay I just solved the problem. That being said, I'm wondering if there is a solution less clumsy than mine. Here is what I did to fix the issue</strong> </p>
  
  <pre><code>! Body of ReInsert
  filename = 'rpriov3.dat' 
  iostat_1 = 0 
  iostat_2 = 0 
  open(newunit = lun, file = filename, status = 'old', iostat = iostat_1) 
  if (iostat_1 == 0) then 
      do while(iostat_2 == 0)             
          if(iostat_2 == 0) then 
              read(lun,*,iostat = iostat_2) dum, real_1,real_2,int_1   
              if(iostat_2 == 0) then !&lt;---- Added this nested if statement
                  print *, dum, real_1,real_2,int_1   
              endif                
              print *, iostat_2                 
          endif
      enddo
  endif
  </code></pre>