Fortran编程——文件输入输出

Fortran读写文本文件。

1 文件写入

此示例演示如何打开新文件以将某些数据写入文件。编译并执行代码时,它会创建文件data1.dat并将x和y数组值写入其中。 然后关闭文件。

        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 文件读取

在这个程序中,我们从文件中读取,我们在最后一个例子中创建了data1.dat,并在屏幕上显示它。

        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

文件读取时,自动判别文件结尾:

        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

自动判别文件结尾可参考如下链接:
[1] Handling End-of-File: the READ Statement Revisited
[2] How to know that we reached EOF in Fortran 77?

猜你喜欢

转载自blog.csdn.net/wokaowokaowokao12345/article/details/127091920
今日推荐