在CentOS系统下,使用Fortran进行文件操作主要依赖于Fortran的内置I/O功能。以下是一些基本的文件操作示例:
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
stop
end if
! 文件操作代码...
close(unit_number)
end program open_file_example
program read_file_example
implicit none
integer :: unit_number, iostat, num_lines
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
stop
end if
num_lines = 0
do
read(unit=unit_number, '(A)', iostat=iostat) line
if (iostat /= 0) exit
num_lines = num_lines + 1
print *, 'Line', num_lines, ':', trim(line)
end do
close(unit_number)
end program read_file_example
program write_file_example
implicit none
integer :: unit_number, iostat
character(len=*) :: filename
filename = 'output.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
stop
end if
write(unit=unit_number, *) 'Hello, World!'
write(unit=unit_number, *) 'This is a test.'
close(unit_number)
end program write_file_example
program append_to_file_example
implicit none
integer :: unit_number, iostat
character(len=*) :: filename
filename = 'output.txt'
unit_number = 20
open(unit=unit_number, file=filename, status='old', position='append', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
write(unit=unit_number, *) 'Appending this line to the file.'
close(unit_number)
end program append_to_file_example
在上述示例中,close(unit_number)
用于关闭文件。确保在完成所有文件操作后调用此语句。
在文件操作过程中,使用iostat
变量来检查错误。如果iostat
不为0,则表示发生了错误。
通过这些基本示例,你应该能够在CentOS系统下使用Fortran进行基本的文件操作。