如何检查文件是否为空?

时间:2016-10-22 20:14:29

标签: fortran fortran90

我有很多文件,在开始阅读文件之前我想检查文件是否为空。

有没有办法在Fortran 90中检查文件是否为空? 我应该使用INQUIRE吗?

1 个答案:

答案 0 :(得分:1)

有点难以理解你的意思并不是空的'。您必须区分几种不同的场景:

  1. 该文件不存在。
  2. 文件存在,但无法读取。 (权限不正确)。
  3. 该文件存在,但根本不包含任何内容(大多数人都会将其描述为'空白'。
  4. 文件存在,包含一些数据,但不完整。
  5. 该文件存在且包含所有数据。
  6. 如果您对任何这些选项可能发生任何担心,最常见的方法是iostat参数的大量使用(如果您的编译器理解Fortran 2003,则为iomsg)。如果给出了这个参数,如果程序没有做某件事但是将这个变量设置为某个非零整数,程序就不会崩溃。

    见这个例子:

     program iotest
        implicit none
        integer :: ios
        character(len=100) :: iomsg
        integer :: iounit
        integer :: i, n
        character(len=*), parameter :: FILENAME='data.dat'
    
        open(newunit=iounit, file=FILENAME, action="READ", iostat=ios, iomsg=iomsg)
        call check(ios, iomsg, "OPEN")
        do i = 1, 10
            read(iounit, *, iostat=ios, iomsg=iomsg) n
            call check(ios, iomsg, "READ")
            print*, n
        end do
        close(iounit, iostat=ios, iomsg=iomsg)
        call check(ios, iomsg, "CLOSE")
    contains
        subroutine check(ios, iomsg, op)
            implicit none
            integer, intent(in) :: ios
            character(len=*), intent(in) :: iomsg, op
            if (ios == 0) return   ! There was no error, continue
            print*, "Error encountered during " // trim(op)
            print*, "Error code: ", ios
            print*, "Error message: " // trim(iomsg)
            STOP 1
        end subroutine check
    end program iotest
    

    如果您只需要大小,可以尝试使用INQUIRE(file=FILENAME, size=iSize)功能。我说试试,因为我在任何Fortran书籍中都找不到关于SIZE关键字的任何文档,但在阅读@IanH后进行测试表明它有效。他认为它是在Fortran 2003中添加的,但我在Fortran 2003手册中找不到任何引用,所以它可能是2008年。

    那就是说,他比我更了解Fortran。

相关问题