在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进行基本的文件操作。