在CentOS系統中,使用Fortran進行文件操作主要依賴于Fortran標準庫中的I/O(輸入/輸出)子程序。以下是一些基本的文件操作步驟和示例代碼:
使用OPEN
語句打開文件,并指定文件名、訪問模式和狀態。
program file_example
implicit none
integer :: unit_number, iostat
character(len=*) :: 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
print *, 'File opened successfully.'
close(unit_number)
end program file_example
使用WRITE
語句將數據寫入文件。
program write_to_file
implicit none
integer :: unit_number, iostat
character(len=10) :: data = 'Hello, World!'
unit_number = 10
write(unit=unit_number, '(A)') data
close(unit_number)
end program write_to_file
使用READ
語句從文件中讀取數據。
program read_from_file
implicit none
integer :: unit_number, iostat
character(len=10) :: data
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
stop
end if
read(unit=unit_number, '(A)') data
print *, 'Data read from file:', data
close(unit_number)
end program read_from_file
使用CLOSE
語句關閉文件。
program close_file
implicit none
integer :: unit_number
unit_number = 10
close(unit=unit_number)
end program close_file
在文件操作過程中,可以使用iostat
參數來檢查錯誤狀態。
program error_handling
implicit none
integer :: unit_number, iostat
character(len=10) :: data
unit_number = 10
open(unit=unit_number, file='nonexistent.txt', status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
read(unit=unit_number, '(A)') data
print *, 'Data read from file:', data
close(unit=unit_number)
end program error_handling
iostat
參數來檢查文件操作的錯誤狀態。通過以上步驟和示例代碼,你可以在CentOS系統中使用Fortran進行基本的文件操作。