Allocation of array for reading strings from a text file

You could read the entire text file into a string using unformatted stream, as done in the code below, and then use the positions of the newlines to determine the length of the longest line.

program read_file_into_string
implicit none
character (len=*), parameter :: fname = "file.txt"
integer :: i,ipos,iu,len_text
integer, parameter :: n = 10
character (len=:), allocatable :: text
open (newunit=iu,file=fname,action="read")
inquire(unit=iu,size=len_text) ! get file size
close (iu)
! allocate string large enough to hold file if possible
allocate (character (len=len_text) :: text)
open (newunit=iu,file=fname,action="read", &
      form="unformatted",access="stream")
read (iu) text ! read file into variable text
ipos = index(text,new_line("")) ! pos of first newline
print "('first line: ',a)","'" // text(1:ipos-1) // "'"
! find position of next-to-last newline character in text
ipos = index(text(:len_text-1),new_line(""),back=.true.)
print "('last line: ',a)", &
      "'" // text(ipos+1:len_text-1) // "'"
end program read_file_into_string

Storing the text you gave in file.txt and running, the output is

first line: 'a'
last line: 'de'
2 Likes