阅读量:2
在CentOS系统下,使用Fortran进行文件的读写操作主要依赖于Fortran的内置I/O功能。以下是一些基本的读写操作示例:
写文件
program write_example
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real, dimension(10) :: data
! 初始化数据
data = [ (i, i=1, 10) ]
! 打开文件
filename = 'example.dat'
open(unit=iounit, file=filename, status='replace', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
! 写数据到文件
write(iounit, *) data
! 关闭文件
close(iounit)
end program write_example
读文件
program read_example
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real, dimension(10) :: data
! 文件名
filename = 'example.dat'
! 打开文件
open(unit=iounit, file=filename, status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
! 读数据从文件
read(iounit, *) data
! 关闭文件
close(iounit)
! 打印读取的数据
print *, 'Data read from file:', data
end program read_example
注意事项
- 文件路径:确保文件路径正确。如果文件不在当前工作目录下,需要提供完整路径。
- 错误处理:使用
iostat参数来检查I/O操作是否成功。 - 文件模式:
status='replace'表示如果文件已存在则替换,status='old'表示文件必须存在。 - 数据格式:Fortran默认使用空格分隔的数据格式,可以使用
format语句自定义读写格式。
高级读写
对于更复杂的文件操作,可以使用Fortran的format语句来指定数据的读写格式。例如:
program advanced_io
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real, dimension(10) :: data
filename = 'example.dat'
open(unit=iounit, file=filename, status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
! 使用format语句读取数据
read(iounit, '(10F8.2)') data
close(iounit)
print *, 'Data read from file:', data
end program advanced_io
在这个例子中,'(10F8.2)'指定了读取10个浮点数,每个浮点数占8个字符宽度,其中2位是小数。
通过这些基本示例,你应该能够在CentOS系统下使用Fortran进行文件的读写操作。
以上就是关于“CentOS下Fortran文件如何读写”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm