Silverfrost Forums

Welcome to our forums

Program to get number of rows from an input data file

24 Oct 2013 10:41 #13219

I have multiple data files with known number of columns (fixed for all files) but unknown number of varying rows. I am trying to write a program that will read an input file and will provide number of rows, n. I attempted to write the code but of course did not work. Any help would be greatly appreciated. Thanks.

PROGRAM num_rows 
IMPLICIT NONE 
INTEGER::n,ierr 
ierr = 0
OPEN (UNIT=3, FILE=seqfname, STATUS='OLD', ACTION='READ', IOSTAT=ierr) 
DO i = 1,n!
READ (3,*,IOSTAT=ierr)xdummy,y(i) 
if (ierr /=0) exit 
END DO 
CLOSE (UNIT = 3) 
WRITE(*,*) number_of_rows
END
24 Oct 2013 11:08 (Edited: 25 Oct 2013 12:47) #13221

You could try something like:

!This program will read a data file containing two columns and 
!write an output data file containing a single column of interest. 
PROGRAM readwrite 
    IMPLICIT NONE 
    INTEGER :: seqnum, nl, mn, nf
    CHARACTER (LEN=11) :: seqfilein
!
    mn = 0   ! max line length
    nf = 0   ! number of valid files
    DO seqnum = 1,999
       WRITE (seqfilein,'(a,I3.3,a)') 'main',seqnum,'.txt'
       CALL READ_WRITE_DATA  (nl, seqfilein)
       if (nl > 0) nf = nf+1 
       mn = max (mn, nl)
    END DO 
    write (*,*) 'number of files',nf
    write (*,*) 'longest file is',mn
END 
 
!&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&a 
SUBROUTINE READ_WRITE_DATA (nl, seqfname) 
    IMPLICIT NONE 
    INTEGER, INTENT(OUT) :: nl
    CHARACTER (LEN=11), INTENT(IN)  :: seqfname 
!
    INTEGER :: i,ierr
    REAL*8  :: x, y
    CHARACTER(LEN=11) :: seqfout    
!
    seqfout = seqfname(1:7)//'.dat'                                           
    OPEN (UNIT=11, FILE=seqfname, STATUS='OLD', ACTION='READ', IOSTAT=ierr)
     if (IERR/=0) then
        WRITE (*,*) ' ERROR OPENING ',seqfname 
        nl = -1
        return
     end if
!
    OPEN (UNIT=12, FILE=seqfout, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ierr) 
     if (IERR/=0) then
        WRITE (*,*) ' ERROR OPENING ',seqfout
        nl = -2
        return
     end if
!
    DO i = 1, huge(i)
       READ  (11,*,IOSTAT=ierr) x, y
       if (ierr /=0) exit 
       WRITE (12,'(F5.2)') y
    END DO 
    nl = i-1
    WRITE (*,*) seqfname,' has',nl,' lines'
    
    CLOSE (UNIT = 11) 
    CLOSE (UNIT = 12) 

END SUBROUTINE READ_WRITE_DATA 

Updated with better error management

25 Oct 2013 12:08 #13222

Thanks Mr. Campbell! This is exactly what I was looking for! Cheers!

Please login to reply.