Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Read a string with unknown length

582 views
Skip to first unread message

Peng Yu

unread,
Jun 13, 2015, 11:07:19 PM6/13/15
to
This URL shows a solution how to read a string with unknown length. But it is too long. I'd expect this operation is relatively common in practice and should have been included in some fortran library so that I can just call a simple function to get it done? Is it available any ware?

http://w3facility.org/question/fortran-95-reading-a-character-string-of-unknown-length/

Regards,
Peng

Thomas Koenig

unread,
Jun 14, 2015, 4:37:09 AM6/14/15
to
Peng Yu <peng...@gmail.com> schrieb:

> This URL shows a solution how to read a string with unknown length. But it
> is too long.

Too long for what?

If you put this into a module and compile with -Os on a x86_64 system, the
resulting assembly file is 298 lines, and the object file has 3.5k.

That is not big.

> I'd expect this operation is relatively common in practice and
> should have been included in some fortran library so that I can just call a
> simple function to get it done? Is it available any ware?

Why not include it in your own sources and run it?

Clive Page

unread,
Jun 14, 2015, 5:23:12 AM6/14/15
to
It's true that 20-odd lines of code is not large in current terms, but
Peng Yu has identified what I think is an omission in modern Fortran.
The character type was ahead of its time when introduced in Fortran77
but has not advanced much since. Allocatable strings can get their
length set on assignment but not when present in a READ statement, and
allocatable strings really only work for scalars.

Just for the benefit of Peng Yu: the traditional way of solving this is
to choose a character length much longer than any line you think you can
possibly encounter, then trim it on output.
For example:

program demo
implicit none
character(len=10000) :: buffer
read(*, '(a)') buffer
write(*,*) 'trimmed length=', len_trim(buffer), trim(buffer)
end program

That's a bit of a bodge, and rather inefficient, but if you want
convenience and efficiency in handling text, Fortran is perhaps not the
best choice of language.

--
Clive Page
0 new messages