溫馨提示×

Ubuntu Fortran如何進行文件操作

小樊
51
2025-05-30 00:12:37
欄目: 智能運維

在Ubuntu上進行Fortran文件操作,你可以使用Fortran標準庫中提供的I/O子例程。以下是一些基本的文件操作示例:

  1. 打開文件
program open_file_example
    implicit none
    integer :: unit_number, iostat
    character(len=*) :: 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
    else
        print *, 'File opened successfully.'
    end if
end program open_file_example
  1. 讀取文件
program read_file_example
    implicit none
    integer :: unit_number, iostat, num_read
    character(len=100) :: line

    unit_number = 10
    open(unit=unit_number, file='example.txt', status='old', action='read', iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error opening file:', iostat
    else
        do
            read(unit_number, '(A)', iostat=iostat) line
            if (iostat /= 0) exit
            print *, line
        end do
    end if

    close(unit_number)
end program read_file_example
  1. 寫入文件
program write_file_example
    implicit none
    integer :: unit_number, iostat
    character(len=*) :: filename

    filename = 'example.txt'
    unit_number = 20

    open(unit=unit_number, file=filename, status='replace', action='write', iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error opening file:', iostat
    else
        write(unit_number, *) 'Hello, World!'
        print *, 'Data written to file successfully.'
    end if

    close(unit_number)
end program write_file_example
  1. 關閉文件
program close_file_example
    implicit none
    integer :: unit_number, iostat

    unit_number = 10

    close(unit=unit_number, iostat=iostat)

    if (iostat /= 0) then
        print *, 'Error closing file:', iostat
    else
        print *, 'File closed successfully.'
    end if
end program close_file_example

在這些示例中,我們使用了open、read、writeclose等I/O子例程來進行文件操作。注意,你需要確保在使用文件之前檢查iostat變量,以確保操作成功。此外,你還可以使用其他I/O子例程和格式化選項來滿足你的需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女