ubuntu

Ubuntu Fortran如何处理文件输入输出

小樊
36
2025-05-11 19:43:52
栏目: 智能运维

在Ubuntu上使用Fortran进行文件输入输出,你需要了解Fortran的I/O语句和文件操作。以下是一些基本的步骤和示例代码,帮助你开始使用Fortran进行文件输入输出。

1. 打开文件

使用OPEN语句打开文件。你需要指定文件名、访问模式(如读、写、追加)、状态(如新建、已存在)等。

program file_io_example
    implicit none
    integer :: unit_number, iostat
    character(len=100) :: filename

    filename = 'example.txt'
    unit_number = 10  ! 选择一个未被使用的单元号

    ! 打开文件进行写入
    open(unit=unit_number, file=filename, status='new', action='write', iostat=iostat)

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

    ! 写入数据到文件
    write(unit_number, *) 'Hello, Fortran!'
    write(unit_number, *) 'This is a test file.'

    ! 关闭文件
    close(unit_number)
end program file_io_example

2. 读取文件

使用READ语句从文件中读取数据。

program file_io_read_example
    implicit none
    integer :: unit_number, iostat
    character(len=100) :: filename

    filename = 'example.txt'
    unit_number = 10  ! 使用之前打开的单元号

    ! 打开文件进行读取
    open(unit=unit_number, file=filename, status='old', action='read', iostat=iostat)

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

    ! 读取数据从文件
    character(len=100) :: line
    read(unit_number, '(A)') line
    print *, 'Read from file:', line

    close(unit_number)
end program file_io_read_example

3. 处理错误

在文件操作中,处理I/O错误是非常重要的。你可以使用iostat参数来检查操作是否成功。

integer :: iostat
open(unit=unit_number, file=filename, status='new', action='write', iostat=iostat)

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

4. 关闭文件

使用CLOSE语句关闭文件,释放资源。

close(unit_number)

5. 使用格式化I/O

Fortran提供了多种格式化I/O方式,可以根据需要选择合适的格式。

! 写入格式化数据
write(unit_number, '(I5, F8.2)') 123, 456.789

! 读取格式化数据
integer :: int_value
real :: real_value
read(unit_number, '(I5, F8.2)') int_value, real_value
print *, 'Read values:', int_value, real_value

通过这些基本步骤,你可以在Ubuntu上使用Fortran进行文件输入输出操作。根据具体需求,你可以进一步扩展和优化代码。

0
看了该问题的人还看了