问题
How do I get the contents of a directory in Fortran 95?
回答1:
shure if we have all the files in the 'inFiles' folder, we first find out how many are there and then we read their names into an array, check this out:
real :: r
integer :: i,reason,NstationFiles,iStation
character(LEN=100), dimension(:), allocatable :: stationFileNames
! get the files
call system('ls ./inFiles > fileContents.txt')
open(31,FILE='fileContents.txt',action="read")
!how many
i = 0
do
read(31,FMT='(a)',iostat=reason) r
if (reason/=0) EXIT
i = i+1
end do
NstationFiles = i
write(verb,'(a,I0)') "Number of station files: " , NstationFiles
allocate(stationFileNames(NstationFiles))
rewind(31)
do i = 1,NstationFiles
read(31,'(a)') stationFileNames(i)
! write(verb,'(a)') trim(stationFileNames(i)) end do close(31)
回答2:
To be pedantic, you don't. There's no intrinsic or such in Fortran 95 that helps you.
On a POSIX system and a recent Fortran compiler, you can use ISO_C_BINDING to create interfaces to the POSIX opendir() and readdir() functions (or readdir_r() if you need thread safety), which allow you to iterate over the directory entries.
回答3:
There is no concept of a directory in Fortran, as such. It reads files. (There are some processors that don't even have a concept of directory).
With that being said, the easiest way would be with SYSTEM. Depends on what you want with that after ...
来源:https://stackoverflow.com/questions/8892741/listing-the-contents-of-a-directory-in-fortran