温馨提示×

CentOS下Fortran文件如何读写

小樊
47
2025-11-22 02:55:14
栏目: 智能运维

在CentOS系统下,使用Fortran进行文件的读写操作主要依赖于Fortran的内置I/O功能。以下是一些基本的读写操作示例:

写文件

program write_example
    implicit none
    integer :: iounit, iostat
    character(len=100) :: filename
    real, dimension(10) :: data

    ! 初始化数据
    data = [ (i, i=1, 10) ]

    ! 打开文件
    filename = 'example.dat'
    open(unit=iounit, file=filename, status='replace', action='write', iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error opening file:', iostat
        stop
    end if

    ! 写数据到文件
    write(iounit, *) data

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

读文件

program read_example
    implicit none
    integer :: iounit, iostat
    character(len=100) :: filename
    real, dimension(10) :: data

    ! 文件名
    filename = 'example.dat'

    ! 打开文件
    open(unit=iounit, file=filename, status='old', action='read', iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error opening file:', iostat
        stop
    end if

    ! 读数据从文件
    read(iounit, *) data

    ! 关闭文件
    close(iounit)

    ! 打印读取的数据
    print *, 'Data read from file:', data
end program read_example

注意事项

  1. 文件路径:确保文件路径正确。如果文件不在当前工作目录下,需要提供完整路径。
  2. 错误处理:使用iostat参数来检查I/O操作是否成功。
  3. 文件模式status='replace'表示如果文件已存在则替换,status='old'表示文件必须存在。
  4. 数据格式:Fortran默认使用空格分隔的数据格式,可以使用format语句自定义读写格式。

高级读写

对于更复杂的文件操作,可以使用Fortran的format语句来指定数据的读写格式。例如:

program advanced_io
    implicit none
    integer :: iounit, iostat
    character(len=100) :: filename
    real, dimension(10) :: data

    filename = 'example.dat'

    open(unit=iounit, file=filename, status='old', action='read', iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error opening file:', iostat
        stop
    end if

    ! 使用format语句读取数据
    read(iounit, '(10F8.2)') data

    close(iounit)

    print *, 'Data read from file:', data
end program advanced_io

在这个例子中,'(10F8.2)'指定了读取10个浮点数,每个浮点数占8个字符宽度,其中2位是小数。

通过这些基本示例,你应该能够在CentOS系统下使用Fortran进行文件的读写操作。

0