在Ubuntu上使用Fortran進行文件輸入輸出,你需要了解Fortran的I/O語句和文件操作。以下是一些基本的步驟和示例代碼,幫助你開始使用Fortran進行文件輸入輸出。
使用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
使用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
在文件操作中,處理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
使用CLOSE語句關閉文件,釋放資源。
close(unit_number)
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進行文件輸入輸出操作。根據具體需求,你可以進一步擴展和優化代碼。