Subroutine that returns a list of files in a directory
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(len=*), | intent(in) | :: | dir | |||
character(len=512), | intent(out), | allocatable, dimension(:) | :: | list | ||
character(len=*), | intent(in), | optional | :: | ext |
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