lseek problem

Rick Schubert rns at se-sd.NCR.COM
Sat Oct 14 01:48:37 AEST 1989


In article <14779 at uhnix1.uh.edu> jsmng at csuna.cs.uh.edu () writes:
>I posted a problem I encountered  with lseek mainly due to my own
>defiency in C. The problem was I was aware of the difference in
>buffered I/O and low lever I/O. I have received a lot of constructive
>comments. They are all similar so I chose one which seems to be quite
>informative to post. Thanks for the contribution.

>>	-- Tim Olson
>>You can't mix lseek and f{scan,get}f.  The later functions use the
>>buffered I/O provided in the stdio package.  What is happening is that
>>on your first fscanf, an attempt is made to read BUFSIZE bytes from
>>the file and place them into the _iob structure.  Once this is done,
>>the fscanf reads out of this buffer.  Lseeks do not affect this buffer
>>at all; they change the actual file pointer (affecting reads and
>>writes).  What you want to use is fseek, which works with the other
>>"f" functions.

Unfortunately, you (jsmng at csuna.cs.uh.edu) chose the wrong response to post
as the right answer.  While much of what Tim said is correct (or at least
correct with traditional Unix implementations of |lseek|/|fseek| -- |lseek|
is not an ANSI library functions; POSIX owns |lseek|, but I don't
know what it says about the relationship between |lseek| and |fseek|), his
explanation doesn't explain why your example failed.  I'm pretty sure there
were correct responses posted, but they have expired on our system.

The immediate problem with your program is that (as I believe others have said)
|lseek| expects an |int| as an argument, and you passed it a |FILE *| argument.
|lseek| will try to interpret the bits of the |FILE *| argument as an integer
to determine what file to manipulate.  It will almost assuredly find garbage
and either do nothing or do something potentially destructive to your address
space.  It is very unlikely that it will do anything constructive regarding
the file you were trying to manipulate.

Now, if, instead of
        FILE    *fp;
        /*...*/
        lseek(fp,/*...*/);
you had,
        lseek(fileno(fp),/*...*/);

then Tim's explanation would have applied.

-- Rick Schubert (rns at se-sd.sandiego.NCR.COM)

Although correct explanations to the original problem were posted and I make
it a policy to not contribute to the problem of multiple correct solutions
being posted, the article I am following up to was posted as the final say
in this matter, and in the three days since the article appeared on my machine,
no articles have appeared here that have corrected this "final say".



More information about the Comp.lang.c mailing list