文件输入/输出#

在 Fortran 中,文件由单元标识符管理。与文件系统的交互主要通过 openinquire 内置过程进行。通常,工作流程是将文件打开到一个单元标识符,读取和/或写入它,然后再次关闭它。

integer :: io
open(newunit=io, file="log.txt")
! ...
close(io)

默认情况下,如果文件不存在,则会创建它并以读写方式打开。写入现有文件将从第一个记录(行)开始,因此默认情况下会覆盖文件。

要创建对文件的只读访问权限,必须使用 statusaction 指定:

integer :: io
open(newunit=io, file="log.txt", status="old", action="read")
read(io, *) a, b
close(io)

如果文件不存在,将发生运行时错误。要检查文件是否存在,然后才能打开它,可以使用 inquire 函数。

logical :: exists
inquire(file="log.txt", exist=exists)
if (exists) then
  ! ...
end if

或者,open 过程可以返回可选的 iostatiomsg

integer :: io, stat
character(len=512) :: msg
open(newunit=io, file="log.txt", status="old", action="read", &
  iostat=stat, iomsg=msg)
if (stat /= 0) then
  print *, trim(msg)
end if

请注意,iomsg 需要一个固定长度的字符变量,该变量具有足够大的存储空间来容纳错误消息。

类似地,写入文件是通过使用 statusaction 关键字完成的。要创建新文件,请使用:

integer :: io
open(newunit=io, file="log.txt", status="new", action="write")
write(io, *) a, b
close(io)

或者,可以使用 status="replace" 覆盖现有文件。强烈建议在确定要使用的 status 之前,首先检查文件是否存在。要追加到输出文件,可以使用 position 关键字显式指定:

integer :: io
open(newunit=io, file="log.txt", position="append", &
  & status="old", action="write")
write(io, *) size(v)
write(io, *) v(:)
close(io)

要重置文件中的位置,可以使用内置过程 rewindbackspacerewind 将重置到第一个记录(行),而 backspace 将返回到前一个记录(行)。

最后,要删除文件,必须先打开文件,然后在关闭后才能删除:

logical :: exists
integer :: io, stat
inquire(file="log.txt", exist=exists)
if (exists) then
  open(file="log.txt", newunit=io, iostat=stat)
  if (stat == 0) close(io, status="delete", iostat=stat)
end if

一个有用的 IO 功能是临时文件,可以使用 status="scratch" 打开。在关闭单元标识符后,它们会自动删除。