swallow(3f) - [M_io] read a file into a character array line by line (LICENSE:MIT)
Synopsis
Description
Options
Examples
Author
License
subroutine swallow(filename,pageout)character(len=*),intent(in) :: filename or integer,intent(in) :: io
character(len=1),allocatable,intent(out) :: pageout(:)
Read an entire file into memory as a character array, one character variable per line.NOTE:
Never casually read an entire file into memory if you can process it per line or in smaller units; as large files can consume unreasonable amounts of memory.
filename filename to read into memory, or LUN (Fortran Logical Unit Number). If filename is a LUN, file must be opened with form=unformatted,access=stream
as in
open(unit=igetunit, file=filename, & & action="read", iomsg=message, & & form="unformatted", access="stream", & & status=old,iostat=ios)
pageout array of characters to hold file
Sample program
program demo_swallow use M_io, only : swallow use M_strings, only : notabs implicit none character(len=4096) :: FILENAME ! file to read character(len=:),allocatable :: pageout(:) ! array to hold file in memory integer :: longest, lines, i, ilen character(len=:),allocatable :: line ! get a filename call get_command_argument(1, FILENAME) ! allocate character array and copy file into it call swallow(FILENAME,pageout) if(.not.allocated(pageout))then write(*,*)*demo_swallow* failed to load file //FILENAME else ! write file from last line to first line longest=len(pageout) lines=size(pageout) allocate(character(len=longest)::line) write(*,*)number of lines is ,lines write(*,*)and length of lines is ,longest write(*,(a))repeat(%,longest+2) do i=lines,1,-1 call notabs(pageout(i),line,ilen) write(*,("%",a,"%"))line enddo write(*,(a))repeat(%,longest+2) deallocate(pageout) ! release memory endif end program demo_swallowGiven
first line second line third lineExpected output
number of lines is 3 and length of lines is 11%%%%%%%%%%%%% %third line % %second line% %first line % %%%%%%%%%%%%%
John S. Urban
MIT License
swallow (3) | November 13, 2019 |