在CentOS上进行Fortran程序的输入输出操作,主要依赖于Fortran语言本身提供的I/O语句和库函数。以下是一些基本的输入输出操作示例:
READ
和WRITE
语句program read_example
implicit none
integer :: i
real :: x, y
print *, "Enter two numbers:"
read *, x, y
print *, "You entered:", x, y
end program read_example
program write_example
implicit none
integer :: i
real :: x = 3.14, y = 2.71
print *, "The value of pi is:", x
print *, "The value of e is:", y
end program write_example
FORMAT
语句FORMAT
语句用于指定数据的格式。
program formatted_read
implicit none
integer :: i
real :: x, y
print *, "Enter two numbers in the format (F5.2, F5.2):"
read *, '(F5.2, F5.2)', iostat=i
if (i /= 0) then
print *, "Error reading input."
else
print *, "You entered:", x, y
end if
end program formatted_read
program formatted_write
implicit none
integer :: i = 10
real :: x = 3.14159, y = 2.71828
print '(I5, F8.3, F8.3)', i, x, y
end program formatted_write
INQUIRE
语句INQUIRE
语句用于查询文件属性或设备状态。
program file_inquiry
implicit none
logical :: exists
inquire(file='example.txt', exist=exists)
if (exists) then
print *, "File exists."
else
print *, "File does not exist."
end if
end program file_inquiry
Fortran也支持文件的读写操作。
program write_to_file
implicit none
integer :: unit_number, i
real, dimension(5) :: data = [1.0, 2.0, 3.0, 4.0, 5.0]
unit_number = 10
open(unit=unit_number, file='data.txt', status='replace', action='write')
do i = 1, size(data)
write(unit_number, '(F8.3)') data(i)
end do
close(unit_number)
end program write_to_file
program read_from_file
implicit none
integer :: unit_number, i
real, dimension(5) :: data
unit_number = 10
open(unit=unit_number, file='data.txt', status='old', action='read')
do i = 1, size(data)
read(unit_number, '(F8.3)') data(i)
end do
close(unit_number)
print *, "Data read from file:", data
end program read_from_file
unit_number
来管理文件单元,避免冲突。通过这些基本的输入输出操作,你可以在CentOS上编写和运行Fortran程序,并进行数据的读取和写入。