Fortran programming - file input and output

Fortran reads and writes text files.

1 file write

This example shows how to open a new file to write some data to the file. When the code is compiled and executed, it creates the file data1.dat and writes the x and y array values ​​into it. Then close the file.

        program outputdata   
            implicit none
            real, dimension(100) :: x, y  
            real, dimension(100) :: p, q
            integer :: i  
            ! data  
            do i=1,100  
                x(i) = i * 0.1 
                y(i) = sin(x(i)) * (1-cos(x(i)/3.0))  
            end do  
            ! output data into a file 
            open(1, file = 'data1.dat', status = 'new')  
            do i=1,100  
                write(1,*) x(i), y(i)   
            end do  
            close(1) 
        end program outputdata


2 file read

In this program, we read from the file, we created data1.dat in the last example, and display it on the screen.

        program outputdata   
            implicit none   
            real, dimension(100) :: p, q
            integer :: i  
            ! opening the file for reading
            open (2, file = 'data1.dat', status = 'old')
            do i = 1,100  
                read(2,*) p(i), q(i)
            end do 
            close(2)
            do i = 1,100  
                write(*,*) p(i), q(i)
            end do 
        end program outputdata

When the file is read, the end of the file is automatically judged:

        program outputdata   
            implicit none   
            real, dimension(100) :: p, q
            integer :: i  
            integer :: io
            ! opening the file for reading
            open (2, file = 'data1.dat', status = 'old')
            do
                read(2,*,IOSTAT=io) p(i), q(i)
                if (io/=0) then
                	exit
                end if
            end do 
            close(2)
        end program outputdata

For automatic determination of the end of the file, please refer to the following link:
[1] Handling End-of-File: the READ Statement Revisited
[2] How to know that we reached EOF in Fortran 77?

Guess you like

Origin blog.csdn.net/wokaowokaowokao12345/article/details/127091920