views:

872

answers:

3

I need a portable function/subroutine to locate the position of the last non-blank character in a string. I've found two options: LEN_TRIM and LNBLNK. However, different compilers seem to have different standards. The official documentation for the following compilers suggests that LEN_TRIM is part of the Fortran 95 standard on the following platforms:

However, it appears that nothing is guaranteed on compilers released before the F95 standard. My experience has been that older compilers might specify either LEN_TRIM or LNBLNK, but not necessarily both. My solution has been to use preprocessor conditionals:

#ifdef USE_LEN_TRIM
        iNameLen = LEN_TRIM(cabase)
        iExtLen = LEN_TRIM(caext)
#else
        iNameLen = LNBLNK(cabase)
        iExtLen = LNBLNK(caext)
#endif

and then pass -DUSE_LEN_TRIM to the preprocessor. However, I am not a big fan of preprocessor conditionals & extra compile-time flags. Do you have any suggestions for a portable (before the Fortran 95 standard) function that locate the position of the last non-blank character in a string?

+2  A: 

Before the standard, I would say no. I've seen the len_trim function implemented by hand on F77 codes. If you want to be standard toward old compilers, then you will have to provide your own implementation as a failsafe, and use a preprocessor conditional to pick what you need.

Stefano Borini
+2  A: 

I'm stuck trying to find if this is a pre-Fortran 95 or not, but does

len(trim(s))

work?

Tim Whitcomb
mhmhmh. looks like it does, although I would not bet on it. tested on both g95 and g77.
Stefano Borini
LEN == F77 standard; TRIM == F95 standard
Pete
+6  A: 

LEN_TRIM is part of the Fortran 95 standard. I am not aware of any simple combination of intrinsics in Fortran 77 that could tackle this (TRIM also appeared with Fortran 95, and wasn't available in Fortran 77). But you can use a simple user function to perform that task if you really want to be portable without relying on compiler intrinsics and preprocessor:

  function lentrim(s)
    implicit none
    character(len=*) :: s
    integer lentrim

    do lentrim = len(s), 1, -1
      if (s(lentrim:lentrim) .ne. ' ') return
    end do
  end function lentrim

(tested with g77 and gfortran; use option -ffree-form to compile free-form source like this).

FX