file - FORTRAN 90 如何找出文件夹中的文件数

标签 file fortran directory fortran90

快速怀疑,我需要读取一个文件夹中的所有文件,但我不知道那里有多少个文件。

我知道如何打开它们,只是不知道何时停止,即何时读取所有文件。

最佳答案

如果你有一定的规则来生成文件名(例如mydata001.dat、mydata002.dat等),那么你可以在每次生成文件名时,用查询 语句,文件是否存在。第一次不存在时,可以停止。下面的程序演示了:

program proba
  implicit none

  character(len=20) :: buffer
  logical :: exist
  integer :: ind

  ind = 1
  fileloop: do
    write(buffer,"(A,I3.3,A)") "mydata", ind, ".dat"
    inquire(file=buffer, exist=exist)
    if (.not. exist) then
      write(*,*) "File '", trim(buffer), "' not found, exiting loop"
      exit
    end if
    write(*,*) "File: '", trim(buffer), "' found."
    ind = ind + 1
  end do fileloop

end program proba

或者,如果无法根据规则生成文件名,您可以使用一些库来获取目录中的文件列表。一种可能是我的 modFileSys库,您可以通过以下方式对任意目录内容执行此操作:

program test_ls
  use filesys_module

  type(dirdesc) :: dir
  character(:), allocatable :: path

  call opendir("./", dir)
  path = dir%next_filename()
  do while (len(path) > 0)
    write(*, "(A)") path
    path = dir%next_filename()
  end do

end program test_ls

关于file - FORTRAN 90 如何找出文件夹中的文件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15787308/

相关文章:

R 使用字符参数调用 Fortran 子例程

c++ - 查找所有文件时未显示文件名

linux - 如何从绝对路径和包文件创建 tar 存档,就好像它们是相对的一样?

Android:打开文件夹对话框

c++ - 在 2 个字符之后插入点,直到 C++ 中的文件末尾

c - 写入文件时获得不同的输出

Fortran 编译错误 - undefined reference

c++ - Fortran 子例程在链接到 C++ 程序时产生 "Undefined symbols"错误

c++ - 在 C++ 中的文件(日志文件)中添加新行

c - 读取结构的连续数组元素并立即打印它直到它到达 c 中的文件末尾