温馨提示×

Ubuntu上Fortran如何进行文件读写操作

小樊
40
2025-11-20 18:56:35
栏目: 智能运维

在Ubuntu上使用Fortran进行文件读写操作,你需要使用Fortran的内置I/O功能。以下是一个简单的示例,展示了如何在Fortran中打开文件、写入数据、读取数据以及关闭文件。

首先,确保你已经安装了Fortran编译器,例如gfortran。如果没有安装,可以通过以下命令安装:

sudo apt update
sudo apt install gfortran

接下来,创建一个名为file_io_example.f90的Fortran源文件,并添加以下代码:

program file_io_example
    implicit none
    integer :: iounit, iostat, ios
    real, dimension(10) :: data = [1.0, 2.0, 3.0, 4.0, 5.0, &
                                  6.0, 7.0, 8.0, 9.0, 10.0]
    character(len=100) :: filename

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

    write(iounit, *) 'Data to be written to the file:'
    write(iounit, '(10F8.2)') data
    close(iounit)

    ! 读取文件
    open(unit=iounit, file=filename, status='old', action='read', iostat=ios)
    if (ios /= 0) then
        print *, 'Error opening file for reading:', ios
        stop
    end if

    read(iounit, *) data
    print *, 'Data read from the file:'
    print *, data
    close(iounit)
end program file_io_example

这个程序首先定义了一个名为data的实数数组,并将其写入名为data.txt的文件中。然后,它从该文件中读取数据并将其打印到屏幕上。

要编译并运行此程序,请在终端中执行以下命令:

gfortran -o file_io_example file_io_example.f90
./file_io_example

这将输出以下内容:

Data to be written to the file:
   1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00   10.00
Data read from the file:
   1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00   10.00

这就是在Ubuntu上使用Fortran进行文件读写操作的基本方法。你可以根据需要修改此示例以满足你的需求。

0