Allocation of array for reading strings from a text file

That is a very useful answer. We could slightly improve the code. Use

inquire (file=file_name, exist=file_exist, size=file_size)

to save the open and close statement at the beginning. Here is a read_lines function that read a text file into an allocatable character:

function read_lines(file_name) result(text)
  character(len=*), intent(in) :: file_name
  character(len=:), allocatable :: text
  integer :: file_unit, file_size
  logical :: file_exist

  inquire (file=file_name, exist=file_exist, size=file_size)
  if (.not. file_exist) error stop &
    & "File '"//file_name//"' not found."

  if (.not. allocated(text)) then
    allocate (character(len=file_size) :: text)
  else if (len(text) /= file_size) then
    deallocate (text)
    allocate (character(len=file_size) :: text)
  end if

  open (newunit=file_unit, file=file_name, action="read", &
    & form="unformatted", access="stream")
  read (file_unit) text
  close (file_unit)
end function read_lines