MorganeMaPh
MorganeMaPh

Reputation: 113

Read CHARACTER string without knowing the length

I have to read input data in my Fortran 77 program. It Looks as following

FILENAME PATH

temperature  ./Data

and then in the Fortran code I proceed as following

CHARACTER*8 FILENAME,PATH

READ(5,'(A80)') CARDIN 

READ(5,*) FILENAME,PATH

but the problem is that I don't know the length of FILENAME and PATH in advance. So what if the user doesn't give names that are not exactly 8? Do you have any idea how I can solve this?

Upvotes: 0

Views: 6317

Answers (2)

Holmz
Holmz

Reputation: 724

One can do it in F77, but this is more F90 in style.

INTEGER*4 FUNCTION LengthString(String)
IMPLICIT NONE
CHARACTER* String
INTEGER*4 I

LengthString = -1 !default is -1 just because.

DO I=LEN(String), 1, -1
  IF(String(I:I) .ne. ' ') THEN
     LengthString = I
     EXIT
  ENDIF
ENDDO

RETURN
END FUNCTION LengthString

And the program could be something like this:

PROGRAM Main
CHARACTER*80 AA
INTEGER*4 LenAA
...
LenAA = LengthString(AA)
IF(LenAA .lt. 1) !error out
...
WRITE(*,10) LenAA, A(1:LenAA)
10 FORMAT('AA(',I4,')="',A,'"')
...

Open statement could look like this:

OPEN(FILE=AA(1:LenAA),...

And the path is the same deal.

NewLongFile = Path(1:LenPath) // '/' // AA(1:LenAA)
Len_NewLongFile = LengthString(NewLongFile)

Upvotes: 1

PeMa
PeMa

Reputation: 1716

I'm not entirely sure what you want to do, but you can use TRIM to "cut" the blanc space:

      Program TEST
      CHARACTER*50 FILENAME,PATH

      READ(*,*) FILENAME,PATH
      WRITE(*,*)TRIM(FILENAME),TRIM(PATH)
      END

Upvotes: 0

Related Questions