在CentOS上进行Fortran文件I/O操作,你需要使用Fortran语言提供的I/O语句和函数。以下是一些基本的文件I/O操作步骤和示例:
使用OPEN语句打开一个文件。
program file_io_example
implicit none
integer :: unit_number, iostat
character(len=100) :: 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
使用READ语句从文件中读取数据。
integer :: num_values
real, dimension(:), allocatable :: data
! 假设文件中第一行是数据的数量
read(unit_number, *) num_values
allocate(data(num_values))
read(unit_number, *) data
使用WRITE语句将数据写入文件。
! 写入一些数据到文件
write(unit_number, *) 'This is a test line.'
! 写入数组数据
write(unit_number, '(10F8.3)') (data(i), i=1, num_values)
使用CLOSE语句关闭文件。
close(unit_number)
以下是一个完整的Fortran程序,演示了如何打开、读取、写入和关闭文件。
program file_io_example
implicit none
integer :: unit_number, iostat, num_values
character(len=100) :: filename
real, dimension(:), allocatable :: data
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
! 读取数据数量
read(unit_number, *) num_values
! 分配数组
allocate(data(num_values))
! 读取数据
read(unit_number, *) data
! 关闭文件
close(unit_number)
! 打印读取的数据
print *, 'Data read from file:'
print *, data
! 写入数据到新文件
open(unit=20, file='output.txt', status='new', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening output file:', iostat
stop
end if
write(20, *) 'This is a test line.'
write(20, '(10F8.3)') (data(i), i=1, num_values)
! 关闭输出文件
close(20)
print *, 'Data written to output.txt'
end program file_io_example
iostat的值。allocate动态分配数组大小,以适应不同大小的数据集。通过这些步骤,你可以在CentOS上使用Fortran进行基本的文件I/O操作。