fileread(3f) - [M_io:READ] read (ie. slurp) a file into a string array (LICENSE:PD)
Synopsis
Description
Options
Examples
Author
License
subroutine fileread(filename,pageout)
character(len=*),intent(in) :: filename or integer,intent(in) :: iocharacter(len=:),allocatable,intent(out) :: pageout(:)
Read an entire file into memory as a character array, one character variable per line.NOTE:
Do not 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=streamas in
open(unit=igetunit, file=filename, & & action="read", iomsg=message, & & form="unformatted", access="stream", & & status=old,iostat=ios)An exception is that although stdin cannot currently generally be treated as a stream file file the data will be read from stdin if the filename is -.
pageout array of characters to hold file
Sample program
program demo_fileread use M_io, only : fileread implicit none character(len=4096) :: FILENAME ! file to read character(len=:),allocatable :: pageout(:) ! array to hold file in memory integer :: longest, lines, i character(len=*),parameter :: gen=(*(g0,1x)) ! get a filename call get_command_argument(1, FILENAME) ! allocate character array and copy file into it call fileread(FILENAME,pageout) if(.not.allocated(pageout))then write(*,gen)*demo_fileread* failed to load file,FILENAME else ! write file from last line to first line longest=len(pageout) lines=size(pageout) write(*,gen)number of lines is,lines write(*,gen)and length of lines is,longest write(*,(a))repeat(%,longest+2) write(*,("%",a,"%"))(trim(pageout(i)),i=lines,1,-1) write(*,(a))repeat(%,longest+2) deallocate(pageout) ! release memory endif end program demo_filereadGiven
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
Public Domain
Nemo Release 3.1 | fileread (3m_io) | October 25, 2024 |