read_file_to_char_array Function

public function read_file_to_char_array(filename, border) result(array)

Read a file into a 2d character array.

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: filename
character(len=1), intent(in), optional :: border

if true, extra border is added with this char

Return Value character(len=1), dimension(:,:), allocatable


Calls

proc~~read_file_to_char_array~~CallsGraph proc~read_file_to_char_array read_file_to_char_array proc~number_of_lines_in_file number_of_lines_in_file proc~read_file_to_char_array->proc~number_of_lines_in_file proc~read_line read_line proc~read_file_to_char_array->proc~read_line

Source Code

    function read_file_to_char_array(filename, border) result(array)
        character(len=*),intent(in) :: filename
        character(len=1),intent(in),optional :: border !! if true, extra border is added with this char
        character(len=1),dimension(:,:),allocatable :: array

        integer :: i, j, iunit, n_lines, n_cols
        character(len=:),allocatable :: line

        open(newunit=iunit, file=filename, status='OLD')
        n_lines = number_of_lines_in_file(iunit)
        line = read_line(iunit); n_cols = len(line)
        rewind(iunit)

        if (present(border)) then
            allocate(array(0:n_lines+1, 0:n_cols+1)) ! padding with border
            array = border
        else
            allocate(array(n_lines, n_cols))
        end if

        do i = 1, n_lines
            line = read_line(iunit)
            do j = 1, n_cols
                array(i,j) = line(j:j)
            end do
        end do
        close(iunit)

    end function read_file_to_char_array