在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_read
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
do
read(unit_number, '(A)', iostat=iostat) line
if (iostat /= 0) exit
print *, 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 = 'example.txt'
unit_number = 10
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_number, *) 'Hello, World!'
write(unit_number, *) 'This is a Fortran file operation example.'
close(unit_number)
end program write_file_example
close(unit_number, iostat=iostat)
if (iostat /= 0) then
print *, 'Error closing file:', iostat
end if
在这些示例中,我们使用了open
、read
、write
和close
语句来进行文件操作。注意,文件操作可能会产生I/O错误,因此我们需要检查iostat
变量的值来确定操作是否成功。
在编写Fortran程序时,请确保你的代码遵循Fortran的语法规则,并根据需要进行适当的调整。