Silverfrost Forums

Welcome to our forums

reading data from txt file

22 Jul 2014 3:51 #14345

I am writing a FORTRAN program that reads data from a text file and writing it to the plato console. the data file looks something like this:

PROGRAM K                                       
 IMPLICIT NONE
 REAL mark(100),sum
 INTEGER n,i
 sum=0
 OPEN(UNIT=5,FILE='marks1.dat')                  
 READ(5,*)n 
 if(n<=0)then
   close(5)
   stop'error:no data'
   endif                                  
 READ(5,*)(mark(i),i=1,n)              
  PRINT *, n,' values read as follows:'
 PRINT '(8f8.0)', (mark(i),i=1,n)
   do i=1,n              
  sum=sum+mark(i)
 END DO
 CLOSE(5)
 PRINT '(a,F6.2)','The average value is ', sum/n
END PROGRAM K 

and my dat file (marks1.dat) is as 10 11 12 12 13 14 15 16 17 18 19 19 20 20
Instead of getting displayed as the same values in the text file, the following is the output 10 values read as follows: 11. 12. 12. 13. 14. 15. 16. 17. 18. 19. The average value is 14.70

Press RETURN to close window . . . the first and some last data is failed to read.(':!:') please help me,thanks so much.

22 Jul 2014 11:50 #14346

Firstly, you have only asked for 10 values to be read and that is what it has done. If the first value in your input file was 13 then all would be read. Secondly why not read all values in the file without having to specify it. For example:

PROGRAM K                                        
 IMPLICIT NONE 
 REAL*8 mark(100),sum 
 INTEGER n,i 
 n = 0
 sum=0d0
 OPEN(UNIT=10,FILE='marks1.dat')                  
 do while(n .lt. 100)
   READ(10,*,end=9999)mark(n+1)
   n = n + 1
 enddo
9999 continue
 PRINT *, n,' values read as follows:' 
 PRINT '(8f8.0)', (mark(i),i=1,n) 
 do i=1,n              
  sum=sum+mark(i) 
 END DO 
 CLOSE(unit=5) 
 PRINT '(a,F6.2)','The average value is ', sum/n 
END PROGRAM K 

There are many other posts on this site which recommend using unit number from 10 upwards as units 1, 2, 5 & 6 are pre-defined as input/output to console and specifically opening, deassigns their default use. I've used 'REAL8' for better precision rather than the standard 'REAL' which is 'REAL4' and has only about 7 decimal digits precision compared to about 17 for REAL8. Later REAL8 will be an advantage when using Clearwin+

Datafile will contain: 11 12 12 13 14 15 16 17 18 19 19 20 20 only. Using the file extension '.dat' is probably no longer a good idea. It seems to be a throwback to the DEC operating systems (Ah! - happy days with TOPS 10 & 20, RSX11, RSTS and VMS - old age causes digression!) when this was common. Windows uses the .dat extension for other system things. If you use .txt, then the Notepad editor will create and edit them by default. Regards Ian

23 Jul 2014 3:33 #14352

Hi IanLambley Thank you very much for your suggestion on how to make my program more efficient. Thanks again for your message. ((dove20))

Please login to reply.