This is the mail archive of the fortran@gcc.gnu.org mailing list for the GNU Fortran project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: strange behavior on end-of-record in READ


On Wed, Oct 19, 2011 at 01:33:32PM -0700, Mark Rashid wrote:
> 
>       program test
>       open (unit = 4, file = 'test.i', status = 'old')
>       read (4, *, iostat = ios) i1, i2, i3, i4
>       write (6, 100) i1, i2, i3, i4, ios
>       read (4, *, iostat = ios) i1, i2, i3, i4
>       write (6, 100) i1, i2, i3, i4, ios
>   100 format (1x, 4(i3, 2x), i6)
>       stop
>       end
> 
> If we make file test.i this:
> 
> 1  2  3  4
> 5  6  7  8
> 
> . . . then we get the expected/correct output, which is:
> 
>    1    2    3    4       0
>    5    6    7    8       0
> 
> But changing test.i to:
> 
> 1  2  3  
> 5  6  7  8
> 
> . . . produces this as output:
> 
>    1    2    3    5       0
>    1    2    3    5      -1
> 
> It appears that the first READ is "wrapping around" and reading the
> first data item from the second line in the input file, and without
> throwing a nonzero IOSTAT.  Stranger still, the second line of output
> suggests that the file is being repositioned, following the first READ,
> to ahead of the *first* line of input.  This might be understandable if
> the first READ were generating an error (in which case the file position
> is indeterminate), but we have that zero IOSTAT on the first READ.  I
> can't make any sense of the -1 for IOSTAT on the second READ.
> 
> I can't see how this behavior is intended, but perhaps?  The standard
> says that the things that constitute an "error" on READ are
> processor-dependent.
> 

First, your question is a general Fortran question, which
should be sent to the comp.lang.fortran newsgroup where 
it will be dissected in excrutiating detail instead of
to the gfortran mailing list.

In short and without citing Sections 9 and 10 of the
Fortran standard, what is happening is:

The first read statement says 'give me 4 values from
file test.i'  Those values (1, 2, 3, and 5) come from
the first 2 records in the file.  At the completion of
the data transfer, the file is positions at the start
of the next record, which happens to be the end-of-file
record.  Your second read statement then tries to get
4 additional values, raises the error condition, and
the values i1, i2, i3, and i4 become undefined.  For
gfortran Fortran, this means the variables retain 
their old values.  Try putting 

      i1 = 42; i2 = 42; i3 = 42; i4 = 42

before the second read statement.

PS: Because of the error condition due to the 2nd read
statement, the second write statement makes your program
non-conforming.

-- 
Steve


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]