在Ubuntu中,使用Fortran處理文件輸入輸出主要涉及到以下幾個步驟:
首先,你需要編寫Fortran代碼來處理文件的輸入和輸出。以下是一個簡單的示例,展示了如何讀取和寫入文件。
program file_io_example
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real, dimension(10) :: data
! 定義文件名
filename = 'data.txt'
! 打開文件進行寫操作
open(unit=iounit, file=filename, status='replace', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file for writing'
stop
end if
! 寫入數據到文件
write(iounit, *) 'This is a test file'
write(iounit, '(10F8.2)') (data(i), i=1, 10)
! 關閉文件
close(iounit)
! 打開文件進行讀操作
open(unit=iounit, file=filename, status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file for reading'
stop
end if
! 讀取數據從文件
read(iounit, *) line
print *, 'Read from file:', line
read(iounit, '(10F8.2)') (data(i), i=1, 10)
! 關閉文件
close(iounit)
end program file_io_example
使用gfortran編譯器編譯你的Fortran代碼。在終端中運行以下命令:
gfortran -o file_io_example file_io_example.f90
這里假設你的源代碼文件名為file_io_example.f90
。
編譯成功后,你可以運行生成的可執行文件:
./file_io_example
運行程序后,你應該會在當前目錄下看到一個名為data.txt
的文件。你可以使用文本編輯器或命令行工具(如cat
)查看文件內容:
cat data.txt
通過以上步驟,你可以在Ubuntu中使用Fortran進行基本的文件輸入輸出操作。根據具體需求,你可以擴展和修改代碼以適應更復雜的場景。