list_files Subroutine

public subroutine list_files(dir, list, ext)

Subroutine that returns a list of files in a directory

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: dir
character(len=512), intent(out), allocatable, dimension(:) :: list
character(len=*), intent(in), optional :: ext

Calls

proc~~list_files~~CallsGraph proc~list_files list_files proc~get_unit~2 get_unit proc~list_files->proc~get_unit~2

Called by

proc~~list_files~~CalledByGraph proc~list_files list_files program~test_files test_files program~test_files->proc~list_files

Source Code

   subroutine list_files(dir, list, ext)
   !! Subroutine that returns a list of files in a directory
   implicit none
   character(len =   *), intent(in )                            :: dir
   character(len = 512), intent(out), allocatable, dimension(:) :: list
   character(len =   *), intent(in ), optional                  :: ext

      character(len = :), allocatable :: out_file

      character(len = 512) :: string
      integer(kind = I4) :: ui, line, i, max_len, ierr

      if ( present(ext) ) then
         out_file = trim(ext) // ".scratch"
         call execute_command_line( "find " // trim(dir) // " -maxdepth 1 -type f -name ""*." // trim(ext) // """ > " // out_file )
      else
         out_file = "files.scratch"
         call execute_command_line("find " // trim(dir) // " -maxdepth 1 -type f > " // out_file)
      endif

      call get_unit(ui)

      open( unit = ui, file = out_file )

         line = 0
         max_len = 0
         do
            string = ' '
            read( unit = ui, fmt = '(a)', iostat = ierr ) string
            if ( ierr /= 0 ) exit
            max_len = max( max_len, len_trim( string ) )
            line = line + 1
         enddo
         if ( max_len > 512 ) stop 'Error list_files: path too long'

         allocate( list(1:line) )

      rewind( ui )

         do i = 1, line
            read( unit = ui, fmt = '(a)' ) list( i )
         enddo

      close( ui )

      deallocate( out_file )

   return
   endsubroutine list_files