在CentOS系统下,Fortran程序的输入输出操作主要依赖于Fortran语言本身提供的I/O语句和函数。以下是一些基本的输入输出操作方法:
READ
和WRITE
语句READ
语句:用于从文件或标准输入(通常是键盘)读取数据。WRITE
语句:用于向文件或标准输出(通常是屏幕)写入数据。program io_example
implicit none
integer :: i
real :: x
! 从标准输入读取数据
print *, "Enter an integer:"
read *, i
print *, "You entered:", i
print *, "Enter a real number:"
read *, x
print *, "You entered:", x
! 向标准输出写入数据
write(*,*) "This is a line of output."
end program io_example
Fortran也支持文件的读写操作。你可以使用OPEN
、READ
、WRITE
、CLOSE
等语句来操作文件。
program file_io_example
implicit none
integer :: unit_number, i
real :: x
character(len=100) :: filename
filename = 'data.txt'
! 打开文件
open(unit=unit_number, file=filename, status='new', action='write')
! 写入数据到文件
write(unit_number,*) "This is a line of data."
! 关闭文件
close(unit_number)
! 重新打开文件以进行读取
open(unit=unit_number, file=filename, status='old', action='read')
! 从文件读取数据
read(unit_number,*) x
print *, "Read from file:", x
! 关闭文件
close(unit_number)
end program file_io_example
FORMAT
语句FORMAT
语句用于定义数据的格式,特别是在读写文件时非常有用。
program format_example
implicit none
integer :: i
real :: x
! 定义格式
format(i5, f8.2)
! 写入数据
write(*, '(i5, f8.2)') 123, 45.678
! 读取数据
read(*, '(i5, f8.2)') i, x
print *, "Read:", i, x
end program format_example
OPEN
语句时,注意指定正确的文件状态(如new
、old
、replace
等)和操作模式(如read
、write
、append
等)。总之,在CentOS系统下编写Fortran程序时,你可以利用Fortran语言本身提供的丰富I/O功能来实现数据的输入输出操作。