Listing the contents of a directory in Fortran [closed]
Asked Answered
S

3

1

How do I get the contents of a directory in Fortran 95?

Sinewy answered 17/1, 2012 at 10:6 Comment(2)
What do you mean "I have to pad it or otherwise it does not go through". What have you tried so far. Is it sufficient to print the contents of a directory to screen, or do you need to store the list of files in a variable?Marseilles
@Marseilles : I was referring to the question itself, too short to be accepted by SO.Sinewy
S
8

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)

Sergo answered 31/7, 2013 at 21:14 Comment(0)
K
6

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.

Knighterrantry answered 17/1, 2012 at 13:44 Comment(4)
Does this language allow to do anything useful except multiplying numbers ?Sinewy
For comparison, can you point out where in the C or C++ standard one can find the functionality to list the contents of a directory?Knighterrantry
one would expect that a standard library for such trivial operations is available out of the box for a language of such age.Sinewy
@StefanoBorini For a language called FormulaTranslator, which mathematical formula exactly do you have in mind for a directory listing? Also, the internet wasn't that fast in the 1950s, so collaboration on a standard library wasn't a thing like today. If you want to compute, Fortran is your friend (~170x faster than Python; ~72000x faster than M$ Excel). I cannot scoop icecream with my car. That doesn't mean it's useless, it's just the wrong tool for the job...Entomophilous
M
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 ...

Munn answered 17/1, 2012 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.