Welcome to AE Resources
Converted document Converted document

FORTRAN 90+: FILE INPUT AND OUTPUT DEMONSTRATION

It is recommended to look at the numerical methods codes where the use of file input and output is demonstrated. Some additional examples using code snippets are included here.
EXAMPLE: FILE INPUT and OUTPUT
SUBROUTINE readFile
	IMPLICIT NONE
	INTEGER :: i, ios, nl
	REAL :: a, b
	!Determine the number of lines in the file
	nl = 0 !Initialize
	DO i = 1,1000,1
		READ (5, *, IOSTAT=ios) a, b !Dummy variable
		!If it’s the end of the file, then exit
		IF (ios /= 0) THEN
			EXIT
		ELSEIF (i == 1000) THEN
			WRITE (*,*) ’Maximum allowable data input reached. (1000 lines)’
		ELSE
			x(i) = a
			Cp(i) = b
			nl = nl + 1
		ENDIF
	ENDDO
	IF (nl == 0) THEN
		WRITE(*,*) ’No data found.  Please check input file.’
		STOP
	ENDIF
END SUBROUTINE readFile
EXAMPLE: OPEN AND CLOSE STATEMENTS
!Read in file
OPEN(10, FILE=’fort.10’)
READ(10,*) n
ALLOCATE(coef(0:4, 0:n))
coef(0:4,0:n) = 0
READ(10,*) start, finish
READ(10,*) actual
DO i = 0,4
	READ(10,*) (coef(i,j), j=0,n)
ENDDO
CLOSE(10)
EXAMPLE: PRINT STATEMENTS
PROGRAM HelloGoodbye
IMPLICIT NONE
INTEGER :: input
input=0
	DO WHILE(input/=1 .and. input/=2)
		PRINT *, "Enter 1 or 2"
		READ(*,*) input
	END DO
	
	IF (input==1) THEN
		PRINT *, "Hello World!"
	ELSE IF (input==2) THEN
		PRINT *, "Goodbye World!"
	END IF
END PROGRAM HelloGoodbye