在Ubuntu上进行Fortran文件的读写操作,你可以使用Fortran的内置I/O功能。以下是一些基本的文件读写操作的示例:
program write_example
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real :: data(10)
! 初始化数据
data = [(i, i=1, 10)]
! 获取一个未使用的I/O单元号
iounit = 10
! 定义文件名
filename = 'datafile.txt'
! 打开文件进行写入
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)
print *, 'Data written to file:', filename
end program write_example
program read_example
implicit none
integer :: iounit, iostat
character(len=100) :: filename
real :: data(10)
! 定义文件名
filename = 'datafile.txt'
! 获取一个未使用的I/O单元号
iounit = 10
! 打开文件进行读取
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:', filename
print *, 'Data:', data
end program read_example
status
参数来指定文件的打开状态,例如'new'
、'old'
、'replace'
等。iostat
参数来检查I/O操作是否成功,并进行相应的错误处理。这些示例展示了如何在Ubuntu上使用Fortran进行基本的文件读写操作。根据你的具体需求,你可以进一步扩展和修改这些代码。