Read a file from a connected unit into a string.
The connected file has to be opened for sequential formatted access. A string will be returned containing the characters read from the file. If there are potential problems arising, they are returned in the error code iError
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
integer, | intent(in) | :: | funit |
File unit to read, has to be opened sequential and formatted. |
||
character(len=*), | intent(out) | :: | string |
String to fill with the content of the file. |
||
integer, | intent(out) | :: | iError |
Error code: 0 = no error 1 = end of string reached before end of file 2 = Unit not connected |
subroutine tem_file_to_string(funit, string, iError) ! --------------------------------------------------------------------------- !> File unit to read, has to be opened sequential and formatted. integer, intent(in) :: funit !> String to fill with the content of the file. character(len=*), intent(out) :: string !> Error code: !! !! 0 = no error !! 1 = end of string reached before end of file !! 2 = Unit not connected integer, intent(out) :: iError ! --------------------------------------------------------------------------- integer :: old_pos, length integer :: stringlen integer :: io logical :: nUnitOpened character(len=PathLen) :: loc_string ! --------------------------------------------------------------------------- string = '' stringlen = len(string) iError = 2 inquire(unit=funit, opened=nUnitOpened) if (nUnitOpened) then ! Go to the start of the file. rewind(funit) old_pos = 0 do ! Read all contents of the scratch file until eof is encountered read(funit, '(a)', iostat=io) loc_string if (io == 0) then length = len_trim(loc_string)+1 ! Only proceed, if the line still fits into the string if (old_pos+length > stringlen) then string(old_pos+1:) = loc_string(:stringlen-old_pos-length+1) iError = 1 EXIT end if string(old_pos+1:old_pos+length) = trim(loc_string)//new_line('A') old_pos = old_pos+length else ! Reached end of the file, exit the loop. iError = 0 EXIT end if end do end if end subroutine tem_file_to_string