[prog] FORTRAN read with dos carriage returns

Almut Behrens almut-behrens at gmx.net
Wed Oct 5 09:44:48 EST 2005


On Tue, Oct 04, 2005 at 05:11:56PM +0000, Conor Daly wrote:
> 
> Anyway, the question is, is there a way in FORTRAN to skip over a \r in a
> read statement?  It's not guaranteed that the \r will always be in the same
> position so I can't just read x characters and then skip one.
> 
> I can do it in C with an 'if(string[i] == '\r') <skip it>' sort of statement
> but I don't know how to do it in Fortran.

g77 should support fgetc(), so you could basically do it as you would in C.
The sample code below simply skips all \r's and should thus work with
both \n or \r\n terminated lines in the input files.
(tested with g77 v3.3.4 -- probably not portable to any other compiler)

BTW, this ugly assembly language like test-and-jump technique of flow
control is certainly not the state of art of Fortran programming...
(you'll likely know how to do it properly)  But mind you, my Fortran
knowledge is more than rusty, and right now I don't feel any need to
polish it ;)

Cheers,
Almut


        character*40 fil
        character*100 buffer
        character ch
        integer i
        integer ret

        write(*,9)
9       format(' '//,' enter input file name')

        read(*,10)fil
10      format(a40)
                                                                   
        write(*,*) 'file name is ',fil

        open (unit=1, file=fil)

        buffer = ''
        i = 1
100     ret = fgetc(1,ch)
        if (ret == -1)    goto 999  ! eof
        if (ch .eq. '\r') goto 100  ! skip \r
        if (ch .eq. '\n') goto 200  ! print line
        buffer(i:i) = ch
        i = i + 1
        goto 100
200     write(*,*) 'string was :',buffer
        i = 1
        goto 100
999     end



More information about the Programming mailing list