在Ubuntu上使用Fortran进行文件读写,你需要了解Fortran的I/O语句,包括open
, read
, write
, 和 close
。以下是一个简单的例子,展示了如何在Fortran中打开一个文件,写入一些数据,然后读取这些数据。
首先,创建一个名为file_io_example.f90
的Fortran源文件,并添加以下代码:
program file_io_example
implicit none
integer :: iounit, iostat, ios
real, dimension(5) :: numbers = [1.0, 2.0, 3.0, 4.0, 5.0]
character(len=100) :: filename
! 定义文件名
filename = 'numbers.txt'
! 打开文件用于写入
open(unit=iounit, file=filename, status='replace', action='write', iostat=ios)
if (ios /= 0) then
print *, 'Error opening file for writing:', ios
stop
end if
! 写入数据到文件
write(iounit, *) numbers
! 关闭文件
close(iounit)
! 打开文件用于读取
open(unit=iounit, file=filename, status='old', action='read', iostat=ios)
if (ios /= 0) then
print *, 'Error opening file for reading:', ios
stop
end if
! 读取数据从文件
read(iounit, *) numbers
! 关闭文件
close(iounit)
! 打印读取的数据
print *, 'Numbers read from file:', numbers
end program file_io_example
这段代码首先定义了一个包含五个实数的数组numbers
和一个文件名filename
。然后,它尝试打开一个文件用于写入,并检查是否有错误发生。如果没有错误,它会将数组写入文件,关闭文件,然后重新打开文件用于读取。读取操作完成后,它会关闭文件并打印出读取的数据。
要编译和运行这个Fortran程序,请在终端中执行以下命令:
gfortran -o file_io_example file_io_example.f90
./file_io_example
这将编译源代码并创建一个名为file_io_example
的可执行文件。运行这个程序,它将创建一个名为numbers.txt
的文件,写入数组中的数据,然后读取并打印这些数据。
请注意,Fortran的I/O操作可能会因为不同的编译器和平台而有所不同。上面的例子使用的是GNU Fortran编译器(gfortran),它是在Ubuntu上常用的Fortran编译器。如果你使用的是不同的编译器,可能需要查阅相应的文档来了解具体的文件I/O操作。