stdlib icon indicating copy to clipboard operation
stdlib copied to clipboard

Internal stream I/O

Open ivan-pi opened this issue 6 months ago • 0 comments

Motivation

In some cases it is necessary to read data from a character string in "stream" mode. Fortran does not support stream access on internal files.

In C this can be done using fread, where the file handle is associated to a character buffer; on POSIX conforming systems, this can be done using fmemopen. In C++ the std::basic_stringstream can be used for this purpose.

An interface in Fortran could look something like this:

! Read data from stream into buffer
!
! buffer ... object where the read data will be stored
! size ... number of bytes to be read
! stream ... the character string to be treated as a stream
! ierr ... error flag
subroutine stream_read(buffer,size,stream,ierr)
   integer, parameter :: ascii = selected_char_kind ("ascii")
   type(*), intent(inout) :: buffer
   integer, intent(in) :: size
   character(len=:,kind=ascii), pointer, intent(inout) :: stream
   integer, intent(out), optional :: ierr
end subroutine

It may be possible to use a deferred-rank object (i.e. dimension(..)) to automatically convey the dimensions of the buffer. But I suppose the element size needs to be communicated separately. This would be similar to how MPI procedures work: https://docs.open-mpi.org/en/v5.0.x/man-openmpi/man3/MPI_Recv.3.html#fortran-2008-syntax

Prior Art

stdlib already contains a similar function to_num_from_stream (spec found here).

Additional Information

Related threads:

  • https://fortran-lang.discourse.group/t/internal-i-o-with-stream-access/8439/1

ivan-pi avatar Aug 06 '24 12:08 ivan-pi