Although interfacing POSIX commands works, a quick and (somewhat) dirty way to do the same is to just use system's directory listing commands through execute_command_line
, redirecting output to a temporary file. Then you can just read that file to get the listing, and delete the file when it is not needed anymore.
A possible Fortran implementation can be (including some error proofing):
subroutine DirList(directory, flags)
use, intrinsic :: iso_fortran_env, only: error_unit
implicit none
character(len=*), intent(in) :: directory
character(len=*), intent(in), optional :: flags
integer :: tempunit, stat
character(len=255) :: filename
call execute_command_line("ls -1"//flags//" "//directory//" > temp", exitstat=stat)
if (stat/=0) then
write(unit=error_unit, fmt="('Error reading directory ',a)") directory
return
end if
open(newunit=tempunit, file="temp", status="old", action="read")
do
read(unit=tempunit, fmt="(a)", iostat=stat) filename
if (stat < 0) exit
print "(a)",trim(filename)
end do
close(unit=tempunit)
call execute_command_line("rm temp")
end subroutine DirList
Here, ls -1
is used, but dir -1
should work on POSIX as well. The -1
flag is used by default so that output is one string per line (this just saves the extra work to read strings till a blank space). The optional argument flags
can be used to add extra flags, if needed.
Such a subroutine can be used for various tasks, e.g.:
call DirList("your-directory") ! List all files and subdirectories
call DirList("your-directory/*.txt" ! List *.txt files only
call DirList("your-directory/*/", "d") ! List subdirectories only
It may look like a "cheap" approach, but it works and has the extra benefit it is not restricted to POSIX systems only. For example, the subroutine above should work on Windows by replacing ls -1
with dir /b
as the system's command for listing files, and rm
with del
for deleting the temporary file. A more sophisticated version could use the pre-processor to set those system commands as appropriate, depending the operating system the code is compiled.
A function returning an allocatable vector containing the file/subdirectory names can be easily implemented by modifying the subroutine above, if needed.