ubuntu

Fortran在Ubuntu中如何进行文件操作

小樊
45
2025-08-29 15:40:16
栏目: 智能运维

在Ubuntu中使用Fortran进行文件操作,你可以使用Fortran内置的I/O功能。以下是一个简单的示例,展示了如何在Fortran程序中打开、读取和写入文件。

首先,确保你已经安装了Fortran编译器,例如gfortran。在Ubuntu终端中输入以下命令来安装它:

sudo apt update
sudo apt install gfortran

接下来,创建一个名为file_operations.f90的Fortran源文件,并输入以下代码:

program file_operations
    implicit none
    integer :: iounit, iostat, ios
    character(len=100) :: filename
    real :: data

    ! 打开文件
    filename = 'data.txt'
    open(unit=iounit, file=filename, status='replace', action='write', iostat=ios)
    if (ios /= 0) then
        print *, 'Error opening file:', ios
        stop
    end if

    ! 写入数据到文件
    do i = 1, 10
        write(iounit, *) i, i**2
    end do

    ! 关闭文件
    close(iounit)

    ! 重新打开文件以进行读取
    open(unit=iounit, file=filename, status='old', action='read', iostat=ios)
    if (ios /= 0) then
        print *, 'Error opening file:', ios
        stop
    end if

    ! 从文件中读取数据
    do
        read(iounit, *, iostat=ios) data
        if (ios /= 0) exit
        print *, 'Read:', data
    end do

    ! 关闭文件
    close(iounit)
end program file_operations

这个程序首先创建一个名为data.txt的文件,并向其中写入1到10的平方。然后,它关闭文件并重新打开以进行读取操作,最后从文件中读取数据并将其打印到屏幕上。

要编译和运行此程序,请在终端中输入以下命令:

gfortran -o file_operations file_operations.f90
./file_operations

这将生成一个名为file_operations的可执行文件,运行它将执行文件操作并显示结果。

0
看了该问题的人还看了